Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

I don’t do a lot with Hibernate directly, but sometimes I do. I had seen Hibernate inheritance before, but I never had to make one. The pattern that was in place was there was a table that had common information. There was another table that had information that was implementation-specific and there were multiple implementations. My job was to add another implementation. To accomplish the writing of the data, they had a Hibernate entity for the common table. This entity was extended by an implementation-specific entity. Then they would populate the entity and save it. Effectively writing to two tables with one logical write.

The InheritanceType is JOINED. This sets it up to be joined on by other tables (e.g. extended). The base entity was defined as follows:

@Table(name = "FundsAudit")
@Inheritance(strategy = InheritanceType.JOINED)
public class FundsAudit {

    @Column(name = "FundTypeKey")
    private String fundTypeKey;



I had to add an @InheritanceType as SINGLE_TABLE. Which basically says a table per entity. I also specified @PrimaryKeyJoinColumn. The referencedColumnName is the name of the column in the inherited table. The name is the name of the column in the entity that is extending the base table. Note that you don’t see that column listed in the entity that is being extended. That table does in fact exist. This is what I came up with to extend the base entity.

@Table(name = "paynearme_audit")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@PrimaryKeyJoinColumn(referencedColumnName = "FundTypeKey", name = "FundTypeKey")
public class PayNearMeAudit extends FundsAudit {

    //@Id  NOTE:  You don't use ID in an entity that is inherited

    @Column(name = "PayNearMe_Order_ID")
    private long payNearMeOrderIdentifier;



Once I have my entities defined, it is very simple to use the object. I use the entity that I created, that extends the base entity. In my code, that is all you see referenced. I have fields from both entities/tables available to me.

PayNearMeAudit payNearMeAudit = new PayNearMeAudit();
payNearMeAudit.setTransactionDateTime(new Date());
payNearMeAudit.setFundTypeKey(new IdGeneratorImpl().generateOrderId(FundingCache.get(Constants.SITE_ID)));
payNearMeAudit.setResponse("{\"payNearMeOrderIdentifier\":\"" + payNearMeOrderIdentifier + "\"}");
payNearMeAudit = payNearMeAuditDao.findByPayNearMeOrderIdentifier(Long.parseLong(payNearMeOrderIdentifier));

I need to ensure that I specify the value of the join column, fundTypeKey. Other than that, it just works. If you are reading the code, you would never have any idea that you were doing anything out of the ordinary.

August 30th, 2016

Posted In: hibernate

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By :