返回

Spring Boot + MyBatis-Plus 项目必备:彻底告别“Property ‘mapperLocations’ was not specified”错误!

后端

解决 MyBatis-Plus 中“Property 'mapperLocations' was not specified”错误

在使用 MyBatis-Plus 进行对象关系映射时,你可能会遇到“Property 'mapperLocations' was not specified”错误。这个错误表明 Spring Boot 无法找到你的 MyBatis XML 映射器文件。解决方法有很多,本文将介绍三种最常见的解决方案。

解决方案 1:在 application.properties 或 application.yml 文件中指定 mapperLocations

首先,你需要在 Spring Boot 的配置文件(application.properties 或 application.yml)中,找到 mybatis-plus.mapper-locations 属性,并为其指定正确的 XML 配置文件路径。

# mybatis-plus 配置
mybatis-plus.mapper-locations=classpath:mapper/*.xml

如果你的 mapper 文件都放在 classpath:mapper 目录下,那么只需要指定这个目录即可。

解决方案 2:在 Java 代码中使用 @MapperScan 注解

如果你不想在配置文件中指定 mapperLocations,也可以在 Java 代码中使用 @MapperScan 注解。

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

这样,MyBatis-Plus 就会自动扫描 com.example.mapper 包及其子包下的所有 Mapper 接口,并自动注册到 Spring 容器中。

解决方案 3:在 pom.xml 或 build.gradle 文件中添加依赖

有时候,你可能会遇到“Property ‘mapperLocations‘ was not specified”错误,但你已经指定了正确的 mapperLocations,这是因为缺少了 MyBatis-Spring 的依赖。

对于 Maven 项目,你需要在 pom.xml 文件中添加如下依赖:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

对于 Gradle 项目,你需要在 build.gradle 文件中添加如下依赖:

implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.2'

常见问题解答

  1. 我指定了 mapperLocations,但仍然收到错误。
    确保你指定的路径正确无误,并且 MyBatis-Plus 能够访问这些文件。

  2. 我使用 @MapperScan,但 MyBatis-Plus 没有扫描到我的 Mapper 接口。
    检查 @MapperScan 注解是否正确配置,并且你的 Mapper 接口符合约定(以 “Mapper” 结尾)。

  3. 我添加了 MyBatis-Spring 依赖,但错误仍然存在。
    确保你使用的 MyBatis-Spring 版本与你的 MyBatis-Plus 版本兼容。

  4. 我试过所有解决方案,但错误仍然存在。
    检查你的项目中是否有冲突的依赖或配置问题。尝试创建一个新的项目,并逐步添加依赖和配置,以识别问题所在。

  5. 如何在 XML 映射器文件中指定多个命名空间?
    mapper 元素中使用 namespace 属性指定命名空间,并在 Mapper 接口中使用 @Namespace 注解映射到该命名空间。