JPA enumerated types mapping. Best approach

前端 未结 3 1607
囚心锁ツ
囚心锁ツ 2020-12-23 11:43

As usual Java enum types have corresponding codes and name description. And Java classes that contain such fields, contain them as Enum:

public enum MyEnum{
         


        
3条回答
  •  长情又很酷
    2020-12-23 12:18

    You can add an enumerated field to your entity by using @Enumerated. The kicker here is that you want to have your cake and eat it too - for consistency's sake, it'd be better to choose either EnumType.ORDINAL or EnumType.STRING.

    Both have their pluses and minuses, which are listed at this site. The big difference appears to be with ordering - if you have EnumType.ORDINAL set, you would run into problems when updating your enum.

    I would encourage you to rethink the way you want to design your table. The string and the integer essentially store the same information - what the enumerated value is - and you can get that back from the database without too much fuss. It'd be better to have an id as a primary key on the table, then have your enumerated type either as string or ordinal value, taking into account the caveats from the link above.

提交回复
热议问题