@MapperScan和@Mapper


我们定义DemoMapper类,但是并没有在该类上定义类似@Service或者@Controller之类的注解,那么为什么可以被Spring管理呢?

 

https://blog.csdn.net/YuenBin128/article/details/80166389

(1)方式一:使用@Mapper注解

       为了让DemoMapper能够让别的类进行引用,我们可以在DemMapper类上添加@Mapper注解:

Java代码   收藏代码
  1. @Mapper  
  2. public interface DemoMapper {  
  3.     @Insert("insert into Demo(name) values(#{name})")  
  4.     @Options(keyProperty="id",keyColumn="id",useGeneratedKeys=true)  
  5.     public void save(Demo demo);  
  6. }  

 

直接在Mapper类上面添加注解@Mapper,这种方式要求每一个mapper类都需要添加此注解,麻烦。

 

(2)方式二:使用@MapperScan注解

       通过使用@MapperScan可以指定要扫描的Mapper类的包的路径,比如:

Java代码   收藏代码
  1. @SpringBootApplication  
  2. @MapperScan("com.kfit.*.mapper")  
  3. public class App {  
  4.     public static void main(String[] args) {  
  5.        SpringApplication.run(App.class, args);  
  6.     }  
  7. }  

 

或者:

Java代码   收藏代码
  1. @SpringBootApplication  
  2. @MapperScan("com.kfit.mapper")  
  3. public class App {  
  4.     public static void main(String[] args) {  
  5.        SpringApplication.run(App.class, args);  
  6.     }  
  7. }  

 

       可以根据包的结构指定不同的表达式。

 

使用@MapperScan注解多个包

可以使用如下的方式指定多个包:

Java代码   收藏代码
  1. @SpringBootApplication  
  2. @MapperScan({"com.kfit.demo","com.kfit.user"})  
  3. public class App {  
  4.     public static void main(String[] args) {  
  5.        SpringApplication.run(App.class, args);  
  6.     }  
  7. }  

 

       如果mapper类没有在Spring Boot主程序可以扫描的包或者子包下面,可以使用如下方式进行配置:

Java代码   收藏代码
  1. @SpringBootApplication  
  2. @MapperScan({"com.kfit.*.mapper","org.kfit.*.mapper"})  
  3. public class App {  
  4.     public static void main(String[] args) {  
  5.        SpringApplication.run(App.class, args);  
  6.     }  
  7. }  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM