公司动态
mapper-locations: classpath:mapper/*.xml配置是必须的吗
不是必须的但要根据你的使用场景来决定是否需要。什么时候可以不配置mapper-locations如果你只使用 MyBatis-Plus 的注解方式编写 SQL如Select、Insert、Update、Delete并且不需要 XML 文件那么mapper-locations配置完全可以省略。示例只使用注解javaMapper public interface DriverInfoMapper extends BaseMapperDriverInfo { // 使用注解方式编写 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 version1.0 encodingUTF-8? !DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd mapper namespacecom.seazon.cloud.mapper.DriverInfoMapper !-- 复杂查询多表关联、动态条件等 -- select idselectByCondition resultTypecom.seazon.cloud.entity.DriverInfo SELECT * FROM driver_info where if testdriverName ! null and driverName ! AND driver_name LIKE CONCAT(%, #{driverName}, %) /if if testage ! null AND age #{age} /if /where /select /mapperjavaMapper public interface DriverInfoMapper extends BaseMapperDriverInfo { // XML 中定义的方法 ListDriverInfo selectByCondition(Param(driverName) String driverName, Param(age) Integer age); }这时必须在配置文件中指定 XML 位置yamlmybatis-plus: mapper-locations: classpath:mapper/*.xml默认值如果你不配置mapper-locationsMyBatis-Plus 的默认值是textclasspath*:/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可以保留配置不影响启动yamlmybatis-plus: mapper-locations: classpath:mapper/*.xml如果你确定只使用注解方式可以省略yamlmybatis-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可以开始写代码了