不是必须的,但要根据你的使用场景来决定是否需要。
什么时候可以不配置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,可以开始写代码了!