mapper-locations: classpath:mapper/*.xml配置是必须的吗
2026/7/23 2:48:48 网站建设 项目流程

不是必须的,但要根据你的使用场景来决定是否需要。


什么时候可以不配置mapper-locations

如果你只使用 MyBatis-Plus 的注解方式编写 SQL(如@Select@Insert@Update@Delete),并且不需要 XML 文件,那么mapper-locations配置完全可以省略。

示例:只使用注解

java

@Mapper public interface DriverInfoMapper extends BaseMapper<DriverInfo> { // 使用注解方式编写 SQL @Select("SELECT * FROM driver_info WHERE driver_no = #{driverNo}") DriverInfo selectByDriverNo(String driverNo); @Insert("INSERT INTO driver_info (driver_name, driver_no, age) VALUES (#{driverName}, #{driverNo}, #{age})") int insertDriver(DriverInfo driver); }

这种情况下,不需要配置mapper-locations


什么时候必须配置mapper-locations

当你需要使用 XML 文件来编写复杂 SQL 时,就必须配置mapper-locations,让 MyBatis-Plus 知道去哪里加载这些 XML 文件。

示例:使用 XML 文件

xml

<!-- src/main/resources/mapper/DriverInfoMapper.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.seazon.cloud.mapper.DriverInfoMapper"> <!-- 复杂查询:多表关联、动态条件等 --> <select id="selectByCondition" resultType="com.seazon.cloud.entity.DriverInfo"> SELECT * FROM driver_info <where> <if test="driverName != null and driverName != ''"> AND driver_name LIKE CONCAT('%', #{driverName}, '%') </if> <if test="age != null"> AND age = #{age} </if> </where> </select> </mapper>

java

@Mapper public interface DriverInfoMapper extends BaseMapper<DriverInfo> { // XML 中定义的方法 List<DriverInfo> selectByCondition(@Param("driverName") String driverName, @Param("age") Integer age); }

这时必须在配置文件中指定 XML 位置:

yaml

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

默认值

如果你不配置mapper-locations,MyBatis-Plus 的默认值是:

text

classpath*:/mapper/**/*.xml

也就是说,即使你不配置,只要你的 XML 文件放在src/main/resources/mapper/目录下(或任意子目录下),MyBatis-Plus 也会自动扫描到。


对比总结

场景是否必须配置mapper-locations说明
只用注解@Select等)❌ 不需要XML 文件根本不存在
用 XML 文件,放在resources/mapper/❌ 不需要配置使用默认值即可
用 XML 文件,放在其他位置✅ 必须配置例如classpath:mybatis/xml/*.xml
同时使用注解 + XML看 XML 位置同上
分页插件等高级功能❌ 不需要分页插件不依赖 XML

建议

如果你不确定将来是否会用 XML,可以保留配置,不影响启动:

yaml

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

如果你确定只使用注解方式,可以省略

yaml

mybatis-plus: # 不需要配置 mapper-locations global-config: db-config: id-type: auto configuration: map-underscore-to-camel-case: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

现在你的项目已经配置好了 MyBatis-Plus,可以开始写代码了!

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询