1、Spring Boot与MyBatis融合的矛盾问题:

Spring家族的使命就是为了简化而生,但是随着Spring的发展壮大,有点事与愿违了。为了坚持初心,Spring家族祭出了一大杀器---Spring Boot。Spring Boot的核心理念是:不建议使用xml文件配置。但是,这对MyBatis来说进退两难,因为MyBatis离不开xml,需要xml来配置sql语句。为了迎合Spring Boot的发展理念,MyBatis官方开发了mybatis-spring-boot-starter,我们要想更少的依赖xml,需要深入的研究mybatis-spring-boot-starter中的用法,尤其是@MapperScan和@Mapper的用法。

2、@MapperScan和@Mapper简介:

在不使用@MapperScan前,我们需要直接在Mapper类上面添加注解@Mapper,这种方式要求每一个Mapper类都需要添加此注解,非常麻烦,属于重复劳动。通过使用@MapperScan注解,可以让我们不用为每个Mapper类都添加@Mapper注解。

3、@Mapper注解的使用

作用:在接口类上添加了@Mapper,在编译之后会生成相应的接口实现类
添加位置:接口类上面,代码如下所示:

  • @Mapper
  • public interface StudentMapper {
  •    //todo
  • }

4、@MapperScan注解的使用

作用:指定要变成实现类的接口所在的包,包下面的所有接口在编译之后都会生成相应的实现类
添加位置:是在Springboot启动类上面添加,

  • @SpringBootApplication
  • @MapperScan("cn.mybatis.mappers")
  • public class SpringbootMybatisDemoApplication {
  •     public static void main(String[] args) {
  •         SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
  •     }
  • }

添加@MapperScan("cn.mybatis.mappers")注解以后,cn.mybatis.mappers包下面的接口类,在编译之后都会生成相应的实现类

另外,使用@MapperScan注解可以作用到多个包,代码如下所示:

  • @SpringBootApplication  
  • @MapperScan({"cn.mybatis.mappers.class","cn.mybatis.mappers.student"})  
  • public class SpringbootMybatisDemoApplication{  
  •     public static void main(String[] args) {  
  •        SpringApplication.run(SpringbootMybatisDemoApplication.class, args);  
  •     }  

5、使用@MapperScan注解注意事项

Spring Boot不建议使用XML文件配置,MyBatis则有点犯难了,官方推荐使用mybatis-spring-boot-starter与Spring Boot整合。

MyBatis官方建议:直接在Mapper类中采用注解的形式操作数据库,通过@MapperScan扫描制定的映射器存放路径,最终不需要加任何注解,也不需要对应的xml文件来配置sql语句。代码如下形式:

  • //不需要加任何注解,也不需要对应的xml文件
  • public interface UserMapper{
  • @Select("select * from user")
  • List<User> getUserList(String userId);
  • }

标签: none

仅有一条评论

  1. swing swing

    很实用

添加新评论