我知道这是一个老问题,但是我发布了答案,因为它可能对其他人有用。
我不得不面对同样的需求,这很难实现,因此在这里您可以找到实现从
enums架构生成枚举的代码。
该代码是用groovy实现的,但是对于Java来说却非常相似。
首先也是 非常重要的一点 ,我必须为我的枚举生成器创建一个单独的项目,因为它将作为要使用它的项目的依赖项。这是 必需的,
因为生成代码的项目必须在编译时运行枚举生成器,因此实现此目的的方法是将枚举生成器添加为依赖项。
具有枚举表的数据库package com.ctg.jooqgenerator.jooqimport org.jooq.pregen.JavaGeneratorimport org.jooq.pregen.JavaWriterimport org.jooq.meta.Databaseimport org.jooq.meta.SchemaDefinitionimport org.jooq.meta.TableDefinitionimport org.slf4j.Loggerimport org.slf4j.LoggerFactoryimport java.sql.ResultSetclass EnumGenerator extends JavaGenerator { private static final String ENUMS_SCHEMA = "enums" private static final Logger log = LoggerFactory.getLogger(EnumGenerator.class) @Override void generateSchema(SchemaDefinition schema) { // Apply custom logic only for `enums` schema. Others schema has regular generation if (schema.name != ENUMS_SCHEMA) { super.generateSchema(schema) return } log.info("Generating enums") log.info("----------------------------------------------------------") Database db = schema.database db.getTables(schema).each { TableDefinition table -> // Prepare enum name from snake_case to CamelCase String enumName = table.name.replaceAll('_([a-z])') { it[1].capitalize() }.capitalize() JavaWriter out = newJavaWriter(new File(getFile(schema).getParentFile(), "${enumName}.java")) log.info("Generating enum: {}.java [input={}, output={}]", enumName, table.name, enumName) printPackage(out, schema) out.println("public enum $enumName {") ResultSet rs = db.connection.prepareStatement("SELECT * FROM ${schema}."${table.name}"").executeQuery() while (rs.next()) { String name = rs.getString('name'), description = rs.getString('description'), s = rs.isLast() ? ";" : "," // Generate enum entry out.tab(1).println("$name("$description")$s") } out.println(""" | private final String description; | | private $enumName(String description) { | this.description = description; | } |} """.stripMargin()) closeJavaWriter(out) } log.info("----------------------------------------------------------") super.generateSchema(schema) }}
将转换为枚举的表如下所示:
-- Table name `account_role` will be translated into `AccountRole`CREATE TABLE enums.account_role ( "name" varchar(100) NOT NULL, description varchar(255) NOT NULL, ConSTRAINT account_role_name_key UNIQUE (name));-- Table entries will be translated into enum entriesINSERT INTO enums.account_role ("name",description) VALUES ('BILLING','Role for contact/address that will be a Billing contact/address'),('PAYMENT','Role for contact/address that will be a Payment contact/address'),('SERVICE','Role for contact/address that will be a Service contact/address'),('SOLD_TO','Role for contact/address that will be a SoldTo contact/address');
此数据定义将导致以下自动生成的枚举AccountRole.java:
package com.congerotechnology.ctgcommon.jooq.enums;public enum AccountRole { BILLING("Role for contact/address that will be a Billing contact/address"), PAYMENT("Role for contact/address that will be a Payment contact/address"), SERVICE("Role for contact/address that will be a Service contact/address"), SOLD_TO("Role for contact/address that will be a SoldTo contact/address"); private final String description; private AccountRole(String description) { this.description = description; }}
主要项目
然后在将使用此枚举生成器的主项目上,我在上设置了以下maven代码
pom.xml:
<dependencies>... <!-- JOOQ custom generator --> <dependency> <groupId>com.ctg</groupId> <artifactId>ctg-jooq-generator</artifactId> <version>0.0.1</version> </dependency>...</dependencies><build>... <plugins> <!-- JOOQ pre generation --> <plugin> <groupId>org.jooq</groupId> <artifactId>jooq-pregen-maven</artifactId> <version>${jooq.version}</version> <executions> <execution> <id>generate-sources</id> <phase>generate-sources</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <jdbc> <driver>org.postgresql.Driver</driver> <url>jdbc:postgresql://${env.DB_URL}</url> <user>${env.DB_USER}</user> <password>${env.DB_PASSWORD}</password> </jdbc> <generator> <name>com.ctg.ctgjooqgenerator.jooq.EnumGenerator</name> <database> <name>org.jooq.meta.postgres.PostgresDatabase</name> <includes>.*</includes> <excludes /> <dateAsTimestamp>true</dateAsTimestamp> <inputSchema>enums</inputSchema> </database> <generate> <deprecated>false</deprecated> <instanceFields>true</instanceFields> </generate> <target> <packageName>com.ctg.ctgcommon.jooq.enums</packageName> <directory>target/generated-sources/jooq-postgres</directory> </target> </generator> </configuration> <dependencies> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>${postgresql.version}</version> </dependency> </dependencies> </plugin> </plugins>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)