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