如何让JOOQ Gradle脚本不重新生成未变更表对应的类?
解决JOOQ代码生成丢失Lombok注解的问题
问题描述
我有一段自动生成JOOQ类的Gradle脚本:
buildscript { repositories { mavenCentral() } dependencies { classpath( 'org.jooq:jooq:3.18.4', 'org.jooq:jooq-codegen:3.18.4', 'org.jooq:jooq-meta:3.18.4', 'org.postgresql:postgresql:42.6.0' ) } } apply plugin: 'java' apply plugin: 'nu.studer.jooq' import org.jooq.codegen.GenerationTool import org.jooq.meta.jaxb.* task generateJooq { def configuration = new Configuration() .withJdbc( new Jdbc() .withDriver('org.postgresql.Driver') .withUrl('jdbc:postgresql://localhost:5432/test') .withUser('postgres') .withPassword('password')) .withGenerator( new Generator() .withDatabase(new Database().withExcludes("databasechangeloglock|databasechangelog").withInputSchema("public")) .withGenerate( new Generate() .withRoutines(false) .withPojos(true) .withDaos(true) ).withTarget( new Target() .withPackageName('com.example.model.jooq') .withDirectory(projectDir.toString() + '/src/main/java') ).withStrategy( new Strategy() .withMatchers( new Matchers() .withTables( new MatchersTableType() .withTableIdentifier( new MatcherRule() .withExpression('$0_Entity') .withTransform(MatcherTransformType.UPPER) ).withPojoClass(new MatcherRule().withExpression('$0_Entity').withTransform(MatcherTransformType.PASCAL)) ) ) ) ) doLast { GenerationTool.generate(configuration) } }
执行数据库迁移后运行generateJooq任务,它会删除所有类并重新生成,导致手动添加的Lombok注解(@Data、@Builder)全部丢失。我希望实现两种效果之一:要么只重新生成变更表对应的类,要么不重新生成整个类,仅在现有类中新增字段。
解决方案
方案1:启用JOOQ增量代码生成
JOOQ 3.19及以上版本支持增量代码生成,仅生成或更新有变更的表对应的类。需要先升级JOOQ版本到3.19+,然后在生成配置中开启增量模式:
.withGenerator( new Generator() .withIncremental(true) // 开启增量生成 .withDatabase(new Database().withExcludes("databasechangeloglock|databasechangelog").withInputSchema("public")) // 其余配置保持不变 )
增量生成会对比数据库元数据与已生成代码的差异,只更新变动部分,不会覆盖未变更类的手动修改。
方案2:自定义子类添加Lombok注解
不在JOOQ自动生成的Pojo类上直接修改,而是创建继承自生成类的子类,在子类上添加Lombok注解:
// JOOQ自动生成的类(禁止手动修改) public class UserEntity { private Long id; private String name; // JOOQ自动生成的getter、setter } // 手动编写的子类,添加Lombok注解 @Data @Builder public class User extends UserEntity { // 直接继承父类字段,无需重复定义 }
这种方式下,即使JOOQ重新生成父类,子类的注解也不会丢失,可正常使用Lombok功能。
方案3:自定义代码生成模板
通过自定义Freemarker模板,让JOOQ生成Pojo时自动带上Lombok注解:
- 从JOOQ的jar包中复制默认Pojo模板(路径
/org/jooq/codegen/templates/Pojo.java)到项目的src/main/resources/jooq-templates目录; - 修改模板,在类定义前添加Lombok注解:
package ${packageName}; import lombok.Data; import lombok.Builder; @Data @Builder public class ${pojoClass} { // 保留模板原有内容 }
- 在Gradle配置中指定自定义模板路径:
.withGenerator( new Generator() .withTemplate(new Template().withPojo("jooq-templates/Pojo.java")) .withDatabase(new Database().withExcludes("databasechangeloglock|databasechangelog").withInputSchema("public")) // 其余配置保持不变 )
这样每次生成的Pojo类都会自动包含Lombok注解,无需手动添加,自然不会出现注解丢失的问题。
内容的提问来源于stack exchange,提问作者man
相关产品推荐
相关产品推荐

