Springboot+mybatis plus找不到mapper.xml的问题解决

  

问题描述:

使用Springboot和mybatis plus开发过程中,出现了找不到mapper.xml的错误,导致无法正常进行数据库操作。

问题原因:

在Springboot中使用mybatis plus进行数据访问时,需要将.xml文件放在classpath根目录下或者mapper接口所在的包下。而有时候我们的项目结构并不是标准的Maven或Gradle项目结构,这就导致了找不到mapper.xml的问题。

解决方案:

  1. 将.xml文件放在classpath根目录下

在resources目录下创建mapper文件夹,并在该文件夹下放置对应的mapper.xml文件。例如,一个User表对应的UserMapper.xml文件应该放置于resources/mapper/UserMapper.xml路径下。

接下来需要在应用配置文件(application.yml或application.properties)中添加对mapper文件夹的配置,示例如下:

mybatis-plus:
  mapper-locations: classpath:mapper/*.xml

这样就可以直接读取classpath下的mapper文件夹中的.xml文件了,无论我们的项目结构如何。

  1. 将.xml文件与mapper接口放在同一个包下

在mapper接口的包下新建一个与mapper接口同名的包,并在该包下放置对应的mapper.xml文件。例如,一个User表对应的UserMapper接口位于com.example.mapper.UserMapper包下,那么UserMapper.xml文件应该放置于com.example.mapper.UserMapper.UserMapper.xml路径下。

需要注意的是,这种方法仅适用于mapper接口较少的情况。

示例一:

将.xml文件放在classpath根目录下,以User表为例:

  1. 在resources目录下创建mapper文件夹
  2. 在mapper文件夹下创建UserMapper.xml文件
  3. 在应用配置文件中添加对mapper文件夹的配置
mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  1. 在UserMapper接口中添加@Mapper注解和@MapperScan注解(如果没有)
@Mapper
public interface UserMapper extends BaseMapper<User> {
} 
@MapperScan("com.example.mapper")
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

这样就可以顺利读取UserMapper.xml文件了。

示例二:

将.xml文件与mapper接口放在同一个包下,以User表为例:

  1. 在com.example.mapper下创建UserMapper文件夹
  2. 在UserMapper文件夹下创建UserMapper.xml文件
  3. 修改UserMapper接口的命名空间
@Mapper
public interface UserMapper extends BaseMapper<User> {
} 
<mapper namespace="com.example.mapper.UserMapper">
</mapper>

这样就可以顺利读取同一包下的UserMapper.xml文件了。

相关文章