Display Hibernate object for unknown parameter DisccriminatorValue for InheritanceType.SINGLE_TABLE

I have a classic Hibernate @Inheritance(strategy=InheritanceType.SINGLE_TABLE) with @DiscriminatorFormula . It is working fine. However, the @DiscriminatorValue database has about 500 different values, and I need to display about 30 of them for Java classes (children), and the rest for mapping to the parent Java class.

The problem can be modeled as an example of inheritance in the Animal class.

 @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorFormula("...") public class Animal implements Serializable { ... @Column public String getName() { ... } } 

So, I have about 30 subclasses of Animal defined in Java code with @DiscriminatorValue . When Hibernate detects an unknown value for the discriminator, then it throws a WrongClassException . However, I need to match these unknown discriminator values ​​with a single object, the best of which is the Animal class. (I only need to use the getName () method in such cases.)

I know that one solution is to put SQL CASE in @DiscriminatorFormula , but then I have to specify all 30 known discriminator values ​​there (plus more when I need to add others). Therefore, I am looking for a more flexible solution.

PS This is an outdated code, so I can’t change the model.

+6
source share
2 answers

tscho pointed me in the right direction, so I managed to find a solution for my case. @DiscriminatorValue evaluates the special values ​​of @DiscriminatorValue("null") and @DiscriminatorValue("not null") . The second is right for me.

 @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorFormula("...") @DiscriminatorValue("not null") public class Animal implements Serializable { ... @Column public String getName() { ... } } 
+6
source

Good news. I just registered this behavior in the new User Guide. This is a JIRA problem.

Basically, you have two options:

  • @DiscriminatorValue("not null") as a return strategy when there is no explicit matching of discriminator values ​​corresponding to the value of the database column.
  • @DiscriminatorValue("null") when the database column value is null. Usually you use this for the base class.

Here is a detailed example on the Hibernate blog.

+2
source

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


All Articles