SpringBoot2.7.X整合MyBatis-Plus及逆向生成CRUD代码
这里使用的
SpringBoot 2.7.3
的版本,在创建项目及数据库表后,完成后需要进行以下操作数据库表结构中需要增加注释
添加POM
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.3</version>
</dependency>
<!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
添加YML
# application.yml
# DataSource设置
spring:
datasource:
url: jdbc:mysql://主机:端口/数据库?serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=true&zeroDateTimeBehavior=CONVERT_TO_NULL
username: 用户名
password: 密码
#mybatis日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:com/.../包名/mapper/xml/*.xml
逆向生成代码
- 根据情况增加
BaseEntity
基类
@Data
@EqualsAndHashCode(callSuper = false)
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("ID")
@TableId(value = "id", type = IdType.ASSIGN_ID)
private String id;
@ApiModelProperty("创建时间")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime create_time;
// @ApiModelProperty("创建时间")
// @TableField(value = "gmt_create", fill = FieldFill.INSERT)
// private LocalDateTime gmtCreate;
// @ApiModelProperty("更新时间")
// @OrderBy(asc = false)
// @TableField(value = "gmt_modified", fill = FieldFill.INSERT_UPDATE)
// private LocalDateTime gmtModified;
}
- 在
test
包下创建CodeGenerator
类
@SpringBootTest
class CodeGenerator {
@Value("${spring.datasource.url}")
String URL;
@Value("${spring.datasource.username}")
String USERNAME;
@Value("${spring.datasource.password}")
String PASSWORD;
@Test
void generateCode() {
// 包路径
String pkgPath = System.getProperty("user.dir") + "/src/main/java";
/* 父包名 */
String parentPath = "包名";
/* 模块名 */
String modulePath = "";
FastAutoGenerator.create(URL, USERNAME, PASSWORD)
/*
全局配置
*/
.globalConfig(
builder ->
builder
// 作者名
.author("作者")
// 注释日期
.commentDate("yyyy-MM-dd")
// 时间策略
// .dateType(DateType.TIME_PACK)
// 开启swagger2
.enableSwagger()
// 覆盖已生成文件
// .fileOverride()
// 指定输出路径
.outputDir(pkgPath)
// 禁止打开输出目录
.disableOpenDir())
/*
包配置
*/
.packageConfig(
builder ->
builder
// 父包名
.parent(parentPath)
// 父包模块名
.moduleName(modulePath))
/*
策略配置
*/
.strategyConfig(
builder ->
builder
/*
Entity 策略配置
*/
.entityBuilder()
// 开启 lombok 模型
.enableLombok()
// 禁用生成 serialVersionUID
// .disableSerialVersionUID()
// 开启生成字段常量
// .enableColumnConstant()
// 开启链式模型
.enableChainModel()
// 设置父类
// .superClass(parentPath + ".common.model.BaseEntity")
.superClass(BaseEntity.class)
// 添加父类公共字段
// .addSuperEntityColumns("gmt_create", "gmt_modified")
.addSuperEntityColumns("create_time")
// 全局主键类型
.idType(IdType.ASSIGN_ID)
// .addTableFills(
// new Column("gmt_create", FieldFill.INSERT),
// new Column("gmt_modified", FieldFill.INSERT_UPDATE))
.addTableFills(new Column("create_time", FieldFill.INSERT))
// 开启 Boolean 类型字段移除 is 前缀
.enableRemoveIsPrefix()
// 乐观锁字段名(数据库)
// .versionColumnName("version")
// 乐观锁属性名(实体)
// .versionPropertyName("version")
// 逻辑删除字段名(数据库)
// .logicDeleteColumnName("is_deleted")
// 逻辑删除属性名(实体)
// .logicDeletePropertyName("deleteFlag")
// 开启生成实体时生成字段注解
.enableTableFieldAnnotation()
// 格式化文件名称
.formatFileName("%sEntity")
/*
Controller 策略配置
*/
.controllerBuilder()
// 开启驼峰转连字符
.enableHyphenStyle()
// 开启生成@RestController 控制器
.enableRestStyle()
/*
Service 策略配置
*/
.serviceBuilder()
// 格式化 service 接口文件名称
.formatServiceFileName("%sService"))
.execute();
}
}
- 若有公共字段,需要重写
MetaObjectHandler
@Component
public class CommonMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
// this.strictInsertFill(metaObject, "gmtModified", LocalDateTime::now, LocalDateTime.class);
}
@Override
public void updateFill(MetaObject metaObject) {
// this.strictUpdateFill(metaObject, "gmtModified", LocalDateTime::now, LocalDateTime.class);
}
}
添加MybatisPlus配置类
@Configuration
@MapperScan("包名.mapper")
public class MybatisPlusConfig {
/** 分页插件 */
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
}
添加Mybatis-Plus日志
# application.yml
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:com/ex/bianque/mapper/xml/*.xml
测试Mybatis-Plus整合效果
在 test
包下创建 MyBatisPlusTest
类
@SpringBootTest
public class MyBatisPlusTest {
@Autowired private RecordService recordService;
@Test
public void testSelect() {
System.out.println(("----- MybatisPlus测试 ------"));
List<XxxEntity> list = xxxdService.list(new QueryWrapper<XxxEntity>().last(" limit 1"));
list.forEach(System.out::println);
}
}
拓展
CRUD 接口:https://baomidou.com/pages/49cc81/#service-crud-接口
SpringBoot2.7.X整合MyBatis-Plus及逆向生成CRUD代码
https://元气码农少女酱.我爱你/417a23402eb8/