generate enum class from table with JOOQ

梦想的初衷 提交于 2019-11-30 03:41:02

问题


I have the following table called YNM:

 id  name
 1   YES
 2   NO 
 3   MAYBE

and want JOOQ to generate the following java enum:

public enum YNM {
   YES,NO,MAYBE;
}

I understand that support for this was dropped in JOOQ 3 for being overly complicated/anti-intuitive. Is there a way of achieving this?

Thanks in advance.


回答1:


Sure, you could re-implement the removed feature on your side in a few steps:

1. Implement the generator for that enum

You would need to override the JavaGenerator to implement the code generation for the translation of your master data (might be several tables) to enums. How that works is entirely up to you, e.g. you could have:

  • Single column master data tables
  • ID/VALUE mapping tables
  • ID/VALUE/Comment mapping tables
  • Other layouts

2. Generate ForcedType configurations for those enums

Whenever such a master data table is referenced, you should re-wire the foreign key column to that enum using a <forcedType/> configuration. This is best done by configuring your code generation programmatically, as that would allow you to have more dynamic control over your jOOQ code generation configuration.

This step is documented more in detail in Bill O'Neil's answer.

3. Prevent the generation of the master data tables

In addition to the above, you should probably remove the master data tables themselves from your generated output. In your case, this should result in the configuration:

<excludes>YNM</excludes>

Or, if you have more than one master data table:

<excludes>YNM|OTHER_MASTER_DATA_TABLE|...</excludes>

Excluding these tables will prevent accessing them from jOOQ client code, as well as remove foreign key information in generated code, which might be confusing.




回答2:


I think you should be able to use an EnumConverter

public class YNMConverter extends EnumConverter<String, YNM > {

    public YNMConverter() {
        super(String.class, YNM.class);
    }
}

You will then need to add it to the codegen as a custom type and a forced type. Here is a programatic example

new CustomType()
.withName("YNM")
.withType(YNM.class.getName())
.withConverter(YNMConverter.class.getName());

new ForcedType()
.withTypes("varchar")
.withName("YNM")
.withExpression(".*ynm.*") // regex to match the column name

You need to add the forced type and custom type to the codegen. This is can be done in maven / xml or programatically



来源:https://stackoverflow.com/questions/46429671/generate-enum-class-from-table-with-jooq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!