6

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

I'd wish to use this dictionary as a Java enum. Moreover, this dictionary values are referenced from a bunch of other tables, so you'd wish to have it a separate table.

The Java enum cannot be an entity itself. I can use the enum attribute (annotated as @Enumerated) in my Entity classes but this will save the enumeration (as an Integer, char or String) in every table that use this enum instead of using a FK to the dictionary table.

How would you implement such use case?
- Create a Dictionary entity with static method producing enum values?
- Modified getter and setter for Dictionary which returns an enum instead of Dictionary instance?
- ...or perhaps you've never needed to persist an enum in a separate table?

Piotr Nowicki
  • 17,914
  • 8
  • 63
  • 82

2 Answers2

0

You can define your dictionary table using integer ID values that match the ordinal numbers of your enum. This is fragile, as many have noted, since you cannot then easily modify your values: JPA relies on the ordinal() method when using the EnumType.ORDINAL modifier on your @Enumerated annotation.

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

The answer for this question shows another option: Sticking with integers in your entity, but translating in your accessors.

Community
  • 1
  • 1
Chris Goldman
  • 307
  • 1
  • 10
0

This can be achieved with this approach.

1. Enum where your can store ID

public enum Gender{
 MALE(1L),
 FEMALE(2L);

private final Long id;

Gender(Long id) {
   this.id= id;
}

public Long getId(){
   return id;
}

2. Related to this enum 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 RefGenderEntity table can now be prepopulated with two values, and your will be fine with foreign keys and regular normal working joins.

Dmitriy Kuzkin
  • 459
  • 4
  • 4