Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the DiscriminatorValue at run time

We have the following classes

@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) // optional annotation as this is default @DiscriminatorColumn(name = "apType", discriminatorType = DiscriminatorType.STRING, length = 255) @DiscriminatorValue("AP") public class ApplicationProcess { } 

And this

@Entity @DiscriminatorValue("APS") public class ApplicationProcessScheme extends ApplicationProcess { } 

Now I need to know at runtime if the ApplicationProcess is of DiscriminatorValue AP or APS. Since this is automatically handled by jpa, I have no way of getting this value.

We are calling a method that takes an ApplicationProcess as parameter, and I want to avoid using instanceof to check what type it is. Would be cooler if I could do something like

applicationProcess.getApType().equals("AP"); 
like image 929
Shervin Asgari Avatar asked Jun 09 '10 11:06

Shervin Asgari


People also ask

How do you find the discriminator column?

Same column name is used for relation FK to FeatureSubtype. Use other name for discriminator or don't use discriminator at all. In Hibernate, discriminator column on joined inheritance is supported but not required. Hibernate is querying all subtables to determine correct subclass.

What is @DiscriminatorValue?

Annotation Type DiscriminatorValueSpecifies the value of the discriminator column for entities of the given type. The DiscriminatorValue annotation can only be specified on a concrete entity class.


2 Answers

You can map your discriminator as a read-only property:

public class ApplicationProcess {       ...      @Column(name = "apType", insertable = false, updatable = false)     private String apType;  } 
like image 138
axtavt Avatar answered Sep 23 '22 06:09

axtavt


I can imagine few cases where it might be helpful, but despite the reason why you need this, you could create on your abstract class method like

@Transient public String getDiscriminatorValue(){     DiscriminatorValue val = this.getClass().getAnnotation( DiscriminatorValue.class );      return val == null ? null : val.value(); } 
like image 38
Wirus Avatar answered Sep 23 '22 06:09

Wirus