在使用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);  
    }  
}  

​

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐