Enumeration-based Dictionary Implementation in JPA 2

Suppose I have a dictionary (i.e. gender: MALE, FEMALE) that is used in my application.

I would like to use this dictionary as a Java enum . In addition, the values ​​of this dictionary refer to many other tables, so you would like to have a separate table .

Java enum cannot be the essence itself. I can use the enum attribute (annotated as @Enumerated ) in my Entity classes, but this will keep the enumeration (like Integer, char or String) in the table each , which uses this enum instead of using FK in the dictionary table.

How to implement this use case?
- Create a Dictionary object with a static method producing enum values?
- A modified getter and setter for a Dictionary that returns enum instead of a Dictionary instance?
-... or maybe you never needed to save enum in a separate table?

+6
source share
2 answers

You can define your dictionary table using integer identifier values ​​that correspond to the serial numbers of your enum . This is fragile, as many have noted, because you cannot easily change your values: JPA relies on the ordinal() method when using EnumType.ORDINAL in your @Enumerated annotation.

Marginally better, you can specify EnumType.STRING and define the primary key column in the dictionary table as VARCHAR with values ​​equal to the names of the enum values. This is still fragile as you can no longer change your enum names.

The answer for this question shows another option: using integers in your entity, but translating into your accessories.

0
source

This can be achieved with this approach.

1. List where you can store the identifier

 public enum Gender{ MALE(1L), FEMALE(2L); private final Long id; Gender(Long id) { this.id= id; } public Long getId(){ return id; } 

2. Related Entum Separate Entity

 public class RefGenderEntity { private Long id; private String value; ...... } 

3. Look at EntityManager # findById

 MyObjectThatStoreIdForGender val = ...... ; RefGenderEntity gender = em.find(RefGenderEntity.class, val.getGenderId()); 

Of course, the RefGenderEntity table can now be pre-populated with two values, and yours will be fine with foreign keys and regular normal working connections.

0
source

Source: https://habr.com/ru/post/901826/