首页 >
文章列表 > Spring Boot MyBatis中@Mapper、@MapperScan和mybatis.mapper-locations的区别是什么?
Spring Boot MyBatis中@Mapper、@MapperScan和mybatis.mapper-locations的区别是什么?
293
2024-12-17

@mapper、@mapperscan、mybatis.mapper-locations:spring mybatis注解区别
在spring mybatis项目中,“@mapper”、“@mapperscan”和“mybatis.mapper-locations”这三个配置项对于指定mapper接口的位置有着不同的作用:
- @mapper:作用在mapper接口上,表示该接口是一个mybatis mapper接口,需要生成代理对象。通常情况下,拥有@mapper注解的接口不需要再进行扫描。
- @mapperscan:作用在启动类上,用于扫描指定包下的mapper接口,并生成代理对象。它与@mapper类似,但扫描范围更广,可以同时扫描多个包下的mapper接口。
- mybatis.mapper-locations:这是一个配置属性,用于在application.properties或yml等配置文件中指定mybatis xml映射文件的路径。它告诉mybatis扫描该路径下的xml文件,并加载其中的sql语句。
示例:
@mapper
public interface usermapper {
...
}
@springbootapplication
@mapperscan("com.example.baseproject.mapper")
public class baseprojectapplication {
...
}
问题的原因:
你遇到的报错是由于没有为mybatis指定xml映射文件的位置。当使用@mapper或@mapperscan时,mybatis会自动扫描项目中的指定路径下的mapper接口,但不会扫描xml文件。因此,你需要在配置文件中通过mybatis.mapper-locations属性指定xml文件所在路径。
正确配置:
mybatis.mapper-locations=classpath:mapper/*.xml
结论:
- @mapper和@mapperscan用于扫描mapper接口并生成代理对象。
- mybatis.mapper-locations用于指定mybatis xml映射文件的路径。
- 当使用@mapper或@mapperscan时,仍然需要在配置文件中指定mybatis.mapper-locations,以便加载sql语句。