版本匹配是个比较麻烦的问题,这是我的配置:
com.baomidou
mybatis-plus-boot-starter
3.5.2
com.baomidou
mybatis-plus-generator
3.5.2
org.freemarker
freemarker
2.3.31
CodeGenerator:
package com.neuedu.hisweb.utils;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.baomidou.mybatisplus.annotation.FieldFill; // 引入正确的枚举类
import org.apache.commons.lang3.StringUtils;
import java.util.Collections;
import java.util.Scanner;
public class CodeGenerator {
private static final String URL = "jdbc:mysql://localhost:3306/his02?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true";
private static final String USERNAME = "root";
private static final String PASSWORD = "1";
private static final String AUTHOR = "xj";
private static final String PARENT_PACKAGE = "com.neuedu.hisweb";
private static final String OUTPUT_DIR = System.getProperty("user.dir") + "/src/main/java";
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入" + tip + ":");
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 获取需要生成的表名
String tables = scanner("表名,多个英文逗号分割");
FastAutoGenerator.create(URL, USERNAME, PASSWORD)
.globalConfig(builder -> {
builder.author(AUTHOR)
.outputDir(OUTPUT_DIR)
.fileOverride()
.disableOpenDir()
.dateType(DateType.ONLY_DATE)
.commentDate("yyyy-MM-dd");
})
.packageConfig(builder -> {
builder.parent(PARENT_PACKAGE)
.entity("entity")
.service("service")
.serviceImpl("service.impl")
.mapper("mapper")
.controller("controller")
.pathInfo(Collections.singletonMap(
OutputFile.xml,
System.getProperty("user.dir") + "/src/main/resources/mapper"
));
})
.strategyConfig(builder -> {
builder.addInclude(tables.split(","))
.entityBuilder()
.enableLombok()
.naming(NamingStrategy.underline_to_camel)
.columnNaming(NamingStrategy.underline_to_camel)
.logicDeleteColumnName("deleted")
.versionColumnName("version")
.addTableFills(
new Column("create_time", FieldFill.INSERT), // 修改为正确的枚举值
new Column("update_time", FieldFill.INSERT_UPDATE) // 修改为正确的枚举值
)
.controllerBuilder()
.enableRestStyle()
.formatFileName("%sController")
.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.mapperBuilder()
.formatMapperFileName("%sMapper")
.formatXmlFileName("%sMapper");
})
.templateEngine(new FreemarkerTemplateEngine())
.execute();
}
}
@Select
、@Insert
等)。resources/mapper
目录下,文件名与 Mapper 接口名对应。确保 application.yml
或 application.properties
中正确配置 MyBatis-Plus:
# application.yml
mybatis-plus:
# Mapper XML 文件路径
mapper-locations: classpath:mapper/*.xml
# 实体扫描,多个package用逗号或者分号分隔
type-aliases-package: com.neuedu.hisweb.entity
configuration:
# 开启驼峰命名
map-underscore-to-camel-case: true
Mapper 接口:
package com.neuedu.hisweb.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.neuedu.hisweb.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper extends BaseMapper {
// 1. 使用注解实现简单查询
@Select("SELECT * FROM user WHERE age > #{age}")
List selectByAge(int age);
// 2. 使用注解实现带参数的插入
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);
// 3. 使用 XML 实现复杂查询(XML 文件中定义该方法)
List selectUserWithDepartment();
}
对应的 XML 文件(resources/mapper/UserMapper.xml
):
id
必须与 Mapper 接口中的方法名一致。@Param
注解为参数命名。mapper-locations
配置正确指向 XML 文件。classpath:mapper/*.xml
或 classpath*:mapper/**/*.xml
。对于复杂的动态 SQL,XML 方式更加灵活:
XML 文件未被加载:
mapper-locations
配置是否正确。resources
目录下的正确位置。方法找不到:
namespace
是否与 Mapper 接口的全限定名一致。id
)是否匹配。依赖问题:
com.baomidou
mybatis-plus-boot-starter
3.5.2
@MapperScan
与 mapper-locations
的功能的兼容性@MapperScan
负责让 Spring 容器识别 Mapper 接口。mapper-locations
负责让 MyBatis-Plus 加载 XML 中的 SQL 定义。@MapperScan("com.neuedu.hisweb.mapper")
的作用
PatientcostsMapper
),并将这些接口注册为 Spring Bean。@Autowired UserMapper
会报错)。mapper-locations: classpath:mapper/*.xml
的作用
PatientcostsMapper.xml
)。@Select
)定义 SQL,则无需配置;若存在 XML 定义的 SQL,则必须配置正确路径。场景示例:
PatientcostsMapper
继承自 BaseMapper
,自动获得 CRUD 方法(无需 XML)。selectByCondition
),且该方法的 SQL 在 PatientcostsMapper.xml
中实现,则必须通过 mapper-locations
配置 XML 路径,否则 MyBatis-Plus 无法找到对应的 SQL 语句。
@MapperScan
解决的是 Mapper 接口的注册问题,mapper-locations
解决的是 XML 映射文件的加载问题,两者功能独立,可同时使用。
为避免混淆,建议按以下规范组织文件:
Mapper 接口位置:
src/main/java/com/neuedu/hisweb/mapper/PatientcostsMapper.java
(与 @MapperScan("com.neuedu.hisweb.mapper")
扫描路径一致)
XML 映射文件位置:
src/main/resources/mapper/PatientcostsMapper.xml
(与 mapper-locations: classpath:mapper/*.xml
配置路径一致)
@Select
)和 XML 定义 SQL,则 XML 配置优先级更高,会覆盖注解中的 SQL。@MapperScan
扫描路径错误(如写成 @MapperScan("com.neuedu.hisweb.dao")
),则 Spring 无法找到 PatientcostsMapper
,导致启动时报错。@MapperScan
的包路径与 Mapper 接口实际路径一致。NoSuchBeanDefinitionException
或 Invalid bound statement
错误,说明配置正确。mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
,执行 SQL 时会打印 XML 或注解中的 SQL 语句,可验证是否正确加载。