首页 > 编程技术 > java

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

发布时间:2021-10-9 12:00

mybatis注解之@Mapper和@MapperScan

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

方式一:使用@Mapper注解

优点:粒度更细

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

方式二:使用@MapperScan注解

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

@SpringBootApplication  
@MapperScan("com.erayt.mapper")  
public class App {  
    public static void main(String[] args) {  
       SpringApplication.run(App.class, args);  
    }  
}  

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

@SpringBootApplication  
@MapperScan("com.erayt.*.mapper")  
public class App {  
    public static void main(String[] args) {  
       SpringApplication.run(App.class, args);  
    }  
}  

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

@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,能够让其他类进行引用;

扫描一个包

扫描多个包

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

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

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

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

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

标签:[!--infotagslink--]

您可能感兴趣的文章: