整合过程
导入依赖:
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.1</version></dependency>
创建测试实体类:
public class User {
private Integer id;
private String name;
private String pwd;
构造方法和getXxx、setXxx
}
创建dao接口,需要标注@Mapper和@Repository注解
@Repository
@Mapper
public interface UserMapper {
/**
* 查询所有用户
*
* @return 返回所有用户对象
*/
List<User> listUsers();
}
创建对应的UserMapper.xml文件,在springboot中xml文件通常放resources里面(和以前一样放dao也不是不行),我们在resources下新建一个mapper文件夹用来存放xxxMapper.xml文件:
mybatis:
#给po类对象起别名
type-aliases-package: com.wjh.springboot.po
#注册映射器,也可以使用mybatis.config-location引入mybatis-config.xml配置文件
mapper-locations: classpath:mapper/*.xml
注意:路径“classpath”指的是资源文件resources。SqlSessionFactory是无需我们自己配置的,springboot会自动把我们配置的数据源注入SqlSessionFactory。
测试类:
@SpringBootTest
class ApplicationTests {
@Autowired //注入属性
private UserMapper userMapper;
@Test
public void test() {
List<User> list = userMapper.listUsers();
for (User user : list) {
System.out.println(user);
}
}
}
@Mapper注解
背景介绍
首先需要知道MyBatis并不是Spring Boot的,它是其它的框架,只不过Spring Boot支持MyBatis的融合。@Mapper注解是MyBatis下的注解,而@Repository是Spring下的注解。Spring的初心是为了简化而生,但随着Spring的发展,需要编写大量的配置文件,有点违背初心。因此,Spring推出Spring Boot来简化大量的xml配置,可以在不写xml配置的情况下依旧保持Spring原有的功能。但是,这对MyBatis来说是进退两难的,因为MyBtis的精华就是xml配置。为了迎合Spring Boot的理念,MyBatis官方推出了mybatis-spring-boot-starter以及@MapperScan和@Mapper注解。
@Mapper注解的作用和使用
@Mapper是用于标注dao层接口的,用来声明该接口是一个Mapper类,对应的xxxMapper.xml就是来实现这个Mapper。由于dao层的接口没有实现类,接口是没有办法创建实例的,因此也就无法注入到ioc容器,就显得和Spring格格不入。因此,@Mapper注解的作用就是在编译时期创建接口的代理对象并注入ioc容器,其它类的xxxMapper属性用@Autowired来获取接口的代理对象。至于为什么使用了@Mapper注解还使用@Repository的原因是:@Mapper注解并不是Spring官方开发的用来注入到ioc容器的注解,即使MyBtis开发的@Mapper注解可以注入到ioc容器,但现在是“Spring吃MyBatis”,而不是“MyBatis吃Spring”。所以如果只用@Mapper而不用@Repository确实已经完成注入到ioc容器,但Spring官方不认识@Mapper注解,所以可能会爆红:
但其实这并不影响正常运行,并且运行一次之后就不会爆红了。由此可知@Repository只是为了形式上注入ioc容器(为了让Spring知道我要把这个类注入ioc容器,解决IDEA爆红而导致不好看的问题),但其实起到实质作用的是MyBatis提供的@Mapper注解。所以,@Mapper和@Repository注解中@Mapper注解是不能少的,只有@Repository注解是不能把接口注入ioc容器的。
@MapperScan注解
如果我们使用@Mapper注解,那么每次添加一个Mapper类就需要添加一个@Mapper注解,这样会比较麻烦,而@MapperScan注解可以指定扫描放Mapper接口的包,相当于给这个包下面的每个Mapper类都加一个@Mapper注解。@MapperScan注解通常加在主类上面,如:
@SpringBootApplication
@MapperScan("com.wjh.springboot.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
参考文章:
http://www.mybatis.cn/archives/862.html
https://www.jianshu.com/p/34f48d31edee
https://www.cnblogs.com/zhi-leaf/p/12167362.html
