好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

mybatis注解之@Mapper和@MapperScan的使用

mybatis注解之@Mapper和@MapperScan

在使用Mybatis持久层框架来操作数据库时,我们可以使用@Mapper注解和@MapperScan注解来将Mapper接口类交给Sprinig进行管理。

方式一:使用@Mapper注解

优点:粒度更细

缺点:直接在Mapper接口类中加@Mapper注解,需要在每一个mapper接口类中都需要添加@Mapper注解,较为繁琐

方式二:使用@MapperScan注解

通过@MapperScan可以指定要扫描的Mapper接口类的包路径

?

1

2

3

4

5

6

7

@SpringBootApplication

@MapperScan ( "com.erayt.mapper" ) 

public class App { 

     public static void main(String[] args) { 

        SpringApplication.run(App. class , args); 

     } 

}

在路径中可以使用 * 作为通配符对包名进行匹配

?

1

2

3

4

5

6

7

@SpringBootApplication

@MapperScan ( "com.erayt.*.mapper" ) 

public class App { 

     public static void main(String[] args) { 

        SpringApplication.run(App. class , args); 

     } 

}

​ 也可以使用@MapperScan注解对多个包进行扫描

?

1

2

3

4

5

6

7

@SpringBootApplication

@MapperScan ( "com.erayt.mapperFirst" , "com.erayt.mapperSecond" ) 

public class App { 

     public static void main(String[] args) { 

        SpringApplication.run(App. class , args); 

     } 

}

@MapperScan和@Mapper区别及理解

作用

扫描项目中的Dao层,将dao接口类注入到Spring,能够让其他类进行引用;

@Mapper :在dao接口类中,添加此注解;麻烦的在于,每个dao接口类都必须添加此注解; @MapperScan :可以指定要扫描的dao接口类的路径,可以在启动类中添加此注解,可替代@Mapper注解(此模块内dao接口类不用都添加@Mapper注解)

扫描一个包

@MapperScan("com.demo.mapper") :扫描指定包中的接口 @MapperScan("com.demo.*.mapper") :一个 * 代表一级包;比如可以扫到com.demo.aaa.mapper,不能扫到com.demo.aaa.bbb.mapper @MapperScan("com.demo.**.mapper") :两个 * 代表任意个包;比如可以扫到com.demo.aaa.mapper,也可以扫到com.demo.aaa.bbb.mapper

扫描多个包

如果dao接口类在主程序可以扫描的包或者子包下面:

?

1

@MapperScan ({ "com.kfit.demo" , "com.kfit.user" })

如果没有,可以使用如下方式进行配置:

?

1

@MapperScan ({ "com.kfit.*.mapper" , "org.kfit.*.mapper" }) 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/weixin_43718648/article/details/94638273

查看更多关于mybatis注解之@Mapper和@MapperScan的使用的详细内容...

  阅读:38次