Question

I want a Java enum class being defined by the values which can be found in a database table.

Is this possible?? How?

I tried to go the other way: I am wondering if it possible to let Eclipselink create a database table for an enum used in Java? Let's say, I have an enum named Status with the values: AVAILABLE and OUT_OF_ORDER. How can I let JPA create the related database table (which should be some kind of lookup table to ensure that there can only be values contained in this table can be used in columns of any other table)?

Another example would be a record library with a class (or table respectively) Record which has a property (column) 'recordType'.

public enum RecordType {
NONE,
LP,
SINGLE
}

How can I tell JPA/Eclipselink to create a table called recordType? Using JPA Tools -> Make persistent ends up in an error in persistence.xml: Listed class RecordType must not be an enum.

Was it helpful?

Solution

Usually, you do not create a table with the possible values of your enum (you already got them on client side!)

You will instead store the value of the enum in a column. JPA allows you to store either the enum value 0,1,2... (highly discouraged) or the string value (AVAILABLE, ... far better!)

@Table(name = "the_name_of_your_table")
public class YourClass {

  @column(name = "the_column_name")
  @Enumerated(EnumType.STRING) // <-Tells JPA to store the enum as a String
  private Status status; 

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top