Saturday, August 15, 2015

Hibernate Discriminator Column Not Getting Auto-populated For InheritanceType.JOINED

I am new to Object Relational Mapping as I have developed database applications with plain JDBC all these years. So I am using Hibernate now and I wanted to have separate extension table for the new subclass that I have created. But I also wanted to treat existing superclass as a separate entity that can be queried without getting results from subclass too. Suppose I have Customer class. And I have created EliteCustomer subclass. I have a requirement that I can query Customer class that doesn't include results from EliteCustomer class. It's a bad example but I guess you got what I needed to do. So I thought of using InheritanceType.JOINED with discriminator column. Then by using discriminator value I can query only superclass objects. But while inserting data through Hibernate, discriminator column was not getting auto-populated and it was storing null value. And if I try to make discriminator column not null, insertion started failing. Now the fact is that Hibernate doesn't really require discriminator column for joined inheritance like some other JPA providers do. It just works fine if you don't mention any discriminator column. But for my case I needed to treat superclass as separate entity while querying, that's why I needed the discriminator column. And JPA spec does support discriminator column for joined inheritance type. So I thought it would be alright. Anyways I found out that some old versions of Hibernate don't support this legacy behaviour. Here is the Jira ticket details that was opened for this issue. As I was using Hibernate 3, I was facing the problem. If you want to turn on support for discriminator column for joined inheritance type, just upgrade to correct 4.2 or 4.3 version and set hibernate.discriminator.ignore_explicit_for_joined to false as mentioned in Jira details. Then Hibernate will start auto-populating value into your discriminator column.