Changing inheritance strategies in branches of a class hierarchy through JPA annotations

Today I ran into an interesting problem. I had an inheritance hierarchy with Hibernate JPA, with the SINGLE_TABLE strategy. Later I added a superclass to the hierarchy that defined the strategy TABLE_PER_CLASS . As a result, the entire hierarchy looked like TABLE_PER_CLASS . This, of course, seems fair if we read @Inheriatance javadoc:

Defines the inheritance strategy that will be used for the hierarchy of entity classes. It is specified in the entity class, which is the root of the hierarchy of feature classes.

Hibernate docs , however, say that:

You can use different matching strategies for different branches of the same inheritance hierarchy.

And continues to be exempted from this statement. This is done using the XML configuration.

So finally my question is: is there a way (possibly a hibernate property) to enable the above xml behavior through annotations and using EntityManager .

+3
source share
1 answer

Well, if you read the β€œInheritance” chapter of the Hibernate documentation a little further :-) you will see that the above example for mixing tables into one hierarchy and strategies of a subclass table is actually nothing more than a table for a hierarchy with the addition of secondary tables:

 <class name="Payment" table="PAYMENT"> <id name="id" type="long" column="PAYMENT_ID"> <generator class="native"/> </id> <discriminator column="PAYMENT_TYPE" type="string"/> <property name="amount" column="AMOUNT"/> ... <subclass name="CreditCardPayment" discriminator-value="CREDIT"> <join table="CREDIT_PAYMENT"> <property name="creditCardType" column="CCTYPE"/> ... </join> </subclass> <subclass name="CashPayment" discriminator-value="CASH"> ... </subclass> </class> 

You can do the same using @SecondaryTable annotation :

 @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="PAYMENT_TYPE") @DiscriminatorValue("PAYMENT") public class Payment { ... } @Entity @DiscriminatorValue("CREDIT") @SecondaryTable(name="CREDIT_PAYMENT", pkJoinColumns={ @PrimaryKeyJoinColumn(name="payment_id", referencedColumnName="id") ) public class CreditCardPayment extends Payment { ... } @Entity @DiscriminatorValue("CASH") public class CashPayment extends Payment { ... } 
+3
source

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


All Articles