释义:

org.mybatis.spring.mapper.ClassPathMapperScanner和tk.mybatis.spring.annotation.MapperScan是两个不同的注解,用于扫描mybatis的mapper接口并自动将其注入到Spring容器中。

  1. org.mybatis.spring.mapper.ClassPathMapperScanner

这是MyBatis官方提供的注解,它是一个类路径Mapper扫描器,用于自动扫描指定包下的所有Mapper接口,并将它们注入到Spring容器中。

通过该注解,可以指定要扫描的包路径和Mapper的注入方式,如下所示:

@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {

}

 

上面的代码表示将com.example.mapper包下的所有Mapper接口注入到Spring容器中。

  1. tk.mybatis.spring.annotation.MapperScan

这是tk.mybatis提供的注解,它也是用于扫描Mapper接口并自动注入到Spring容器中。与org.mybatis.spring.mapper.ClassPathMapperScanner不同的是,它支持使用Mapper接口的注解来自定义SQL语句。

通过该注解,可以指定要扫描的包路径、Mapper的注入方式和Mapper接口上的注解,如下所示:

@Configuration
@MapperScan(basePackages = "com.example.mapper", annotationClass = MyMapper.class)
public class MyBatisConfig {

}

 

 上面的代码表示将com.example.mapper包下所有具有@MyMapper注解的Mapper接口注入到Spring容器中。这样,我们就可以在Mapper接口中使用自定义的SQL语句了。

主要区别:

  1. 扫描方式不同

org.mybatis.spring.mapper.ClassPathMapperScanner是通过扫描指定包路径下的所有Mapper接口,自动将它们注入到Spring容器中。

而tk.mybatis.spring.annotation.MapperScan则支持扩展Mapper接口,即在Mapper接口中添加注解来自定义SQL语句,然后通过扫描指定包路径下所有具有指定注解的Mapper接口,并将它们注入到Spring容器中。

  1. 依赖的包不同

org.mybatis.spring.mapper.ClassPathMapperScanner是MyBatis官方提供的注解,依赖于mybatis-spring包。

而tk.mybatis.spring.annotation.MapperScan是tk.mybatis提供的注解,依赖于tk.mybatis.mapper-spring-boot-starter包。

  1. 扫描效率不同

由于tk.mybatis.spring.annotation.MapperScan支持扩展Mapper接口,需要对Mapper接口进行解析,因此在大规模项目中,扫描效率可能会稍低于org.mybatis.spring.mapper.ClassPathMapperScanner。

综上所述,两者都是用于扫描Mapper接口并自动将其注入到Spring容器中的注解,但是它们的使用方式和功能略有不同,需要根据具体的项目需求来选择使用哪一个。

 

由于项目mybatis相关包引用了 tk.mybatis

使用pagehelper-spring-boot-starter 插件时,默认引用org.mybatis,存在扫描告警

WARN  org.mybatis.spring.mapper.ClassPathMapperScanner - No MyBatis mapper was found in '[com.xxx.xxx.xxx]' package. Please check your configuration.

启动类增加mapper扫描:

@MapperScan("com.xxx.xxx")

去除分页插件的依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </exclusion>
    </exclusions>
</dependency>

 

Logo

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

更多推荐