Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SINGLE_TABLE inheritance strategy using enums as discriminator value

Is it possible to use an enum as a discriminator value when using SINGLE_TABLE inheritance strategy?

like image 798
Bauna Avatar asked Sep 03 '10 20:09

Bauna


People also ask

What is discriminator value in JPA?

The discriminator column is always in the table of the base entity. It holds a different value for records of each class, allowing the JPA runtime to determine what class of object each row represents. The DiscriminatorColumn annotation represents a discriminator column.

What is the use of discriminator column in hibernate?

In case of table per class hierarchy an discriminator column is added by the hibernate framework that specifies the type of the record. It is mainly used to distinguish the record. To specify this, discriminator subelement of class must be specified. The subclass subelement of class, specifies the subclass.

How is inheritance implemented in hibernate?

There are three inheritance mapping strategies defined in the hibernate: Table Per Hierarchy. Table Per Concrete class. Table Per Subclass.

What is discriminator value?

javax.persistence @Target(value=TYPE) @Retention(value=RUNTIME) public @interface DiscriminatorValue. Is used to specify the value of the discriminator column for entities of the given type. The DiscriminatorValue annotation can only be specified on a concrete entity class.


1 Answers

If what you are trying to achieve is to not to duplicate the discriminator values, there is a simple workaround.

@Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="FREQUENCY",     discriminatorType=DiscriminatorType.STRING )     public abstract class Event  { }  @Entity @DiscriminatorValue(value=Frequency.Values.WEEKLY) public class WeeklyEvent extends Event {     … }  public enum Frequency {     DAILY(Values.DAILY),     WEEKLY(Values.WEEKLY),     MONTHLY(Values.MONTHLY);          private String value;      …      public static class Values {         public static final String DAILY = "D";         public static final String WEEKLY = "W";         public static final String MONTHLY = "M";     }    } 

Nothing to do with Hibernate/JPA really, but better than having to maintain the values in multiple places.

like image 126
Asa Avatar answered Sep 28 '22 08:09

Asa