一、核心概念
- 实体类(Entity)
- POJO对象,与数据库表字段一一对应
- 使用注解配置映射关系:
@TableName
,@TableId
,@TableField
- 代码生成器(AutoGenerator)
- MyBatis-Plus 的核心工具类
- 可生成:Entity、Mapper、Service、Controller
二、详细操作步骤(基于Spring Boot)
步骤1:添加依赖
<dependencies>
<!-- MyBatis-Plus 启动器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<!-- 代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.3.1</version>
</dependency>
<!-- 模板引擎(选Freemarker) -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
</dependencies>
步骤2:创建代码生成器配置类
public class CodeGenerator {
public static void main(String[] args) {
AutoGenerator generator = new AutoGenerator();
// 1. 全局配置
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
globalConfig.setAuthor("YourName");
globalConfig.setOpen(false); // 生成后不打开文件夹
globalConfig.setFileOverride(true); // 覆盖已有文件
globalConfig.setSwagger2(true); // 开启Swagger注解
generator.setGlobalConfig(globalConfig);
// 2. 数据源配置
DataSourceConfig dataSource = new DataSourceConfig();
dataSource.setUrl("jdbc:mysql://localhost:3306/your_db?useSSL=false&serverTimezone=UTC");
dataSource.setDriverName("com.mysql.cj.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("123456");
generator.setDataSource(dataSource);
// 3. 包配置
PackageConfig packageConfig = new PackageConfig();
packageConfig.setParent("com.example.project");
packageConfig.setEntity("entity");
packageConfig.setMapper("mapper");
generator.setPackageInfo(packageConfig);
// 4. 策略配置(关键!)
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel); // 表名转驼峰
strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 列名转驼峰
strategy.setEntityLombokModel(true); // 使用Lombok
strategy.setRestControllerStyle(true); // RESTful控制器
strategy.setInclude("user", "order"); // 要生成的表名
strategy.setControllerMappingHyphenStyle(true); // URL中使用连字符
strategy.setTablePrefix("tbl_"); // 忽略表前缀
generator.setStrategy(strategy);
// 5. 模板引擎
generator.setTemplateEngine(new FreemarkerTemplateEngine());
generator.execute(); // 执行生成
}
}
步骤3:运行生成器
直接运行 CodeGenerator.main()
方法,生成的文件将出现在:
src/main/java
└── com
└── example
└── project
├── entity # 实体类
├── mapper # Mapper接口
└── service # Service层
三、常见错误及解决方案
表字段无法映射
- 错误:
Unknown column 'xxx' in 'field list'
- 解决:检查
@TableField(value = "db_column")
或使用strategy.setFieldNaming()
统一策略
- 错误:
Lombok注解无效
- 确保IDE安装了Lombok插件
- 检查依赖是否冲突:
spring-boot-starter
中排除spring-boot-starter-logging
生成代码乱码
- 在全局配置中添加:
globalConfig.setFileOverride(true); globalConfig.setCharset(StandardCharsets.UTF_8.name());
- 在全局配置中添加:
四、注意事项
敏感字段排除
在策略配置中忽略密码字段:strategy.setExclude("password"); // 不生成此字段
逻辑删除字段
实体类中添加注解:@TableLogic private Integer deleted; // 1=删除, 0=未删
自定义类型转换
处理数据库datetime与LocalDateTime:@TableField(typeHandler = LocalDateTimeTypeHandler.class) private LocalDateTime createTime;
五、使用技巧
自定义模板
复制mybatis-plus-generator
源码中的/templates
到项目resources
,修改后指定路径:TemplateConfig tc = new TemplateConfig(); tc.setEntity("/templates/entity.java.ftl"); generator.setTemplate(tc);
字段自动填充
实体类中添加:@TableField(fill = FieldFill.INSERT) private LocalDateTime createTime;
实现
MetaObjectHandler
接口完成自动填充逻辑
六、最佳实践与性能优化
实体类精简
- 只保留与数据库对应的字段
- 避免在实体类中添加业务逻辑
索引字段优化
在频繁查询的字段上添加索引提示:@TableField(exist = false) private String indexHint; // 非数据库字段
在Mapper.xml中动态拼接:
USE INDEX(${indexHint})
结果映射缓存
启用MyBatis二级缓存(需评估数据一致性要求):@TableName(value = "user", resultMap = "userMap") public class User { ... }
超大字段延迟加载
分离大字段到单独实体:@TableField(exist = false) private UserDetail detail; // 通过join查询加载
七、生成结果示例(User.java)
@Data
@TableName("tbl_user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String username;
@TableField(select = false) // 查询时隐藏
private String password;
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@Version // 乐观锁
private Integer version;
}
执行流程总结:
- 配置数据源 → 2. 设置包路径 → 3. 定义生成策略 → 4. 选择模板引擎 → 5. 执行生成