Hibernate Made Easy
Simplified Data Persistence with Hibernate & JPA Annotations
Suggested Retail Price:   $54.98
Current Amazon Purchase Price:   $54.98
When you buy through us on Amazon:   $45.98
You won't find a better price!
Buy through us...Help support the site.
Most Popular Videos
'Cuz some people don't like reading...
Hibernate JPA Video CBT Tutorials Setting up the environment  Setting Up Hibernate
Hibernate and RSA IRAD Rational Software Architect Application Developer CBT Tutorial  Hibernate & Rational (IRAD)
Hibernate JPA Training  Many to Many Associations
Java Persistence With Hibernate Tutorials  Inheritance Mapping
Working with Compund Primary Keys  Compound Primary Keys
Hibernate and Eclipse Tools CBT Tutorial  Using Hibernate & Eclipse
Most Popular Purchases
What people are buying from us...
Popular Hibernate Purchases  Hibernate Made Easy
Popular Hibernate JPA Books  Harnessing Hibernate
The Best Spring and Hibernate Books  Java Persistence w Hibernate
Java Persistence API Books  Spring in Action
Popular Spring and JBoss Books  What is WebSphere?
Popular Spring and JBoss Books  JSR168 Portlet Programming
Most Popular Tutorials
High hit reads on this site...
Hibernate and JPA Links  How Hibernate Works
Hibernate and JPA Free Tutorials  Recommended Books
Hibernate and JPA Simple Examples  Coding Advanced DAOs
Hibernate and JPA Free CBTs  Using The Criteria API
Hibernate and JPA Simple Examples  What is Hibernate?
Win Yourself $100!!!
The 100% Error Free Code Challenge...

The $100 Code Challenge - No Code Errors, Guaranteed!!!
Learn How to Win a Benjamin

HardCore Hibernate
Yeah, you need this book, too...
Hibernate and JPA Simple Examples

If my book makes it Easy, this book makes Hibernate Hardcore. This is the reference standard...You need it.

Read My Review
My Other Books & Stuff
Other decent books of mine :)...
Sun Certified Java Associate SCJA Study Guide  Java Associate Study Guide
SCJA Mock Exam Questions  SCJA Questions Guide
JSR-168 Portlet Development Book  JSR168 Portlet Programming
WebSphere Introduction and Support Book  What is WebSphere?
The Simpsons is based on Pickering Ontario  Pickering is Springfield
Oshawa Ontario, Discerning Bombs A book about like in Oshawa Ontario  Discerning Bombs on Oshawa
A Good Book on Hibernate and JPA the Java Persistence API  Hibernate Made Easy
Is Amazon Psychic?
Amazon thinks you'll like this...

Friendly Links
Websites we like...
Hibernate and JPA Links  JavaRanch: Big Moose Saloon
Hibernate and JPA Free Tutorials  Apache.org
Hibernate and JPA Free CBTs  Pickering is Springfield
Hibernate and JPA Simple Examples  Hibernate.org
Hibernate and JPA Simple Examples  mysql.org
Hibernate and JPA Simple Examples  Coast to Coast
Hibernate and JPA Simple Examples  What is IBM WebSphere?
Hibernate and JPA Simple Examples  Desktop Tower Defense
down caret hibernate jpaAre you Harnessing It?
One of the three books you need...
Harnessing Hibernate Book by James Elliott (Author), Tim O'Brien (Author), Ryan Fowler (Author)
Read My Review
Is Amazon Psychic?
Amazon thinks you'll like this...

What is WebSphere?
I wrote this... I know you'll love it...
WebSphere: What is WebSphere? Java J2EE JEE Portal and Beyond

Buy it now!
SCJA Java Study Guide
Written with your success in mind...
WebSphere: What is WebSphere? Java J2EE JEE Portal and Beyond

Get Java Certified by Sun
The SCJA Exam Questions
I wrote this, too. A Great Exam Prep...
WebSphere: What is WebSphere? Java J2EE JEE Portal and Beyond

Get Sun Java Certified
Portlet Programming
Do you Portal? Then you need this...
WebSphere: What is WebSphere? Java J2EE JEE Portal and Beyond

I Even Made Portlets Real Easy :)
Is Google Clairvoyant?
Google thinks you'll like this...
Please Spread the Word!
Why keep HiberBook a secret???







If you found this site helpful, please tell other people about it. I'd really, really appreciate it.

Most Popular Purchases
What people are buying from us...
Popular Hibernate Purchases  Hibernate Made Easy
Popular Hibernate JPA Books  Harnessing Hibernate
The Best Spring and Hibernate Books  Java Persistence w Hibernate
Java Persistence API Books  Spring in Action
Popular Spring and JBoss Books  What is WebSphere?
Popular Spring and JBoss Books  JSR168 Portlet Programming
Most Popular Videos
'Cuz some people don't like reading...
Hibernate JPA Video CBT Tutorials Setting up the environment  Setting Up Hibernate
Hibernate and RSA IRAD Rational Software Architect Application Developer CBT Tutorial  Hibernate & Rational (IRAD)
Hibernate JPA Training  Many to Many Associations
Java Persistence With Hibernate Tutorials  Inheritance Mapping
Working with Compund Primary Keys  Compound Primary Keys
Hibernate and Eclipse Tools CBT Tutorial  Using Hibernate & Eclipse
Inheritance Mapping with JPA Annotated JavaBeans and Hibernate
How inheritance is mapped to a database with Hibernate...

Inheritance Mapping

In no other place in J2EE development does the divide between application design and database persistence become quite so pronounced as it does when we attempt to map an inheritance hierarchy to a relational database. Inheritance mapping is a difficult thing to do, because databases don't really have any concept that is equivalent to inheritance, while at the same time, inheritance is a central part of every object-oriented domain model.

There are a number of different ways to map inheritance hierarchies to a database, with some options being better than others, and each option having its own set of drawbacks.

This tutorial will explore and contrast the three key mechanisms for mapping an object-oriented, inheritance hierarchy, into a relational database and its tables.

The Inheritance Model

To demonstrate inheritance mapping, I'm going to use a very simple hierarchy of three classes, with the Ancestor class being at the top, the Parent class being in the middle, and the Child class being at the bottom.

The Ancestor-Parent-Child Class Diagram

parent_child_ancestor_class_diagram_mapping_inheritance_with_hiberante_and_JPA.gif

The Ancestor class will declare a property of type id, along with a nationality property of type String:

package com.examscam.mappings; 
import javax.persistence.*;
@Entity
public class Ancestor {
  private Long id;
  private String nationality;
  @Id
  @GeneratedValue
  public Long getId() {return id;}
  public void setId(Long id) {this.id = id;}
  public String getNationality() {return nationality;}
  public void setNationality(String nationality) {
    this.nationality = nationality;
  }
}

The Parent class inherits all of the properties of the Ancestor, and declares a new String property called lastName:

package com.examscam.mappings;
import javax.persistence.*;
@Entity
public class  Parentextends Ancestor{
  private String lastName;
  public String getLastName() {return lastName;}
  public void setLastName(String lastName) {
        this.lastName = lastName;
  }
}

The Child class will extend the Parent class, thus inheriting all of the properties defined in both the Parent and Ancestor classes. Furthermore, the Child class will declare one new String property called firstName:

package com.examscam.mappings;
import javax.persistence.*;
@Entity
public class Child extends Parent {
  private String firstName;
  public String getFirstName() {return firstName;}
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
}

Inheritance Strategies

class_diagram_javax.persistence.InheritanceType_with_hibernate_and_JPA_tutorial.gifHibernate provides three separate options for mapping inheritance hierarchies:

  • TABLE_PER_CLASS
  • JOINED
  • SINGLE_TABLE (the default)

To specify a strategy, you simply place the @Inheritance annotation after the @Entity tag on the class at the top of your class hierarchy, which in this case, would be the Ancestor class. From there, you specify the strategy attribute, which can be set to any one of the three values the InheritanceType enum can take. So, to specify a TABLE_PER_CLASS inheritance strategy, the Ancestor class declaration would look like this:

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Ancestor {    }

Using the TABLE_PER_CLASS inheritance strategy, Hibernate expects three separate tables to be defined in the database, with each table containing the aggregate of all of the declared and inherited properties of the associated class. As a result, the ancestor table would only have two properties, namely the id and nationality fields, whereas the child table duplicates these properties, adds in columns for the Parent's lastName property, and then adds fields for the locally declared firstName property.

erd_diagram_parent_child_ancestor_with_hibernate_and_JPA_tutorial.gif

Joined Table Inheritance

One of the ugly aspects of the TABLE_PER_CLASS inheritance type is the fact that properties get duplicated down the class hierarchy. For example, why should the child table declare columns of type id and nationality when they are already defined in the ancestor table? The JOINED inheritance type addresses this problem by having tables only maintain data that maps directly to the properties in the associated class. Subclasses are then linked to their inherited properties through common primary key fields in the tables, linking as UNION joins at runtime.

To use a JOIN for mapping inheritance, all we have to do is edit the @Inheritance annotation of the Ancestor class, and set the strategy attribute to InheritanceType.JOINED:

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Ancestor { ... }

When using a JOINED strategy for our problem domain, Hibernate expects three database tables, with each table mapping to the various properties defined in each class. The id field then forms a union between tables. So, if an Ancestor instance is saved, a record will be created in only the ancestor table, whereas if a Child instance is created, the fields of the instance will be saved in all three tables, with the records in each table associated, or joined, through a common value for the id field. In essence, the class hierarchy of an instance is JOINED together from all of the individual tables.

joined_Inheritance_Type_Mapping_parent_child_ancestor_with_hibernate_and_JPA_tutorial.gif

The Single Table Inheritance Strategy

So, one of the problems with the TABLE_PER_CLASS inheritance strategy was that sub-classes re-defined properties in their corresponding database tables that were already defined in tables that mapped to parent classes. The JOINED table strategy addresses this deficiency by having the database tables that map to classes only define columns that map to properties for that particular class. A join between the primary key column of tables making up an object's class hierarchy makes it possible to re-create a given entity at runtime. However, the JOINED strategy does have its own set of problems, not the least of which is its inefficiency.

Single_Table_Type_Mapping_parent_child_ancestor_with_hibernate_and_JPA_tutorial.gifImagine you wanted to get a list of all of the Child objects? In that case, the database would have to issue a select * statement against the child, parent and ancestor tables, as properties of a Child instance are spread out over all three tables. This isn't an efficient process at all. Furthermore, three classes tightly joined together by a common primary key, mapped between tables with a one-to-one relationship, could just as easily be flattened out into a single table without any complex primary key joins at all. That is exactly what the third, and often preferential method for mapping class hierarchies, utilizes. The third and final strategy for mapping inheritance is the SINGLE_TABLE strategy.

For our problem domain, in order to use the SINGLE_TABLE strategy, we must change the strategy attribute of the @Inheritance annotation to the value of InheritanceType.SINGLE_TABLE. With this inheritance strategy, all of the properties on the entire class hierarchy are defined in a single table, along with an extra field, named DTYPE, that keeps track of the Java class type associated with the given record.

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Ancestor { }

Benefits of the Single Table Inheritance Type

The single table inheritance type is often the best choice for performing inheritance mapping. First of all, it minimizes the number of tables that need to be queried, which can be significant for large class hierarchies. Furthermore, mapping associations can be very difficult with other strategies.

For example, imagine we were using a single class per table strategy, and we decided an Ancestor could be associated in a one to one manner with another type, say a Location type. Since this relationship would be true for all subclasses, and given the fact that associations are implemented at the database level by foreign keys, we would have to add a new foreign key column to every table that was based on a sub-class of Ancestor. In a large class hierarchy, adding those foreign key fields would be extremely onerous and error prone. On the other hand, with the single table inheritance strategy, only one column would need to be added to one table, which would be a much, much simpler process.

Testing the InheritanceType.SINGLE_TABLE

Here's a little main method you can use to test the single table inheritance type with the Ancestor, Parent and Child classes:

public static void main(String args[]) {
  Ancestor a = new Ancestor();
  a.setNationality("Korean");

  Parent p = new Parent();
  p.setNationality("Jewish");  p.setLastName("Steinberg");

  Child c = new Child();
  c.setNationality("Irish"); 
  c.setLastName("McKenzie");
  c.setFirstName("Cameron");

  Session session = HibernateUtil.beginTransaction();
  session.save(a); session.save(p); session.save(c);
  HibernateUtil.commitTransaction();
}

Saving an Inheritance Hierarchy

When we run the main method that saves an instance of an Ancestor, Parent and Child class, we see the following output in the Hibernate log files:

Hibernate:
insert into Ancestor (nationality, DTYPE) values (?, 'Ancestor')
Hibernate:
insert into Ancestor (nationality, lastName, DTYPE) values (?, ?, 'Parent')
Hibernate:
insert into Ancestor (nationality, lastName, firstName, DTYPE) values (?, ?, ?, 'Child')

As you can see, each record gets saved into the table named after the top of the class hierarchy, which in this case is Ancestor. However, in the actually SQL, Hibernate hard-codes the class type, be it Ancestor, Parent or Child, into the SQL statement, so that the DTYPE field can be used to positively identify the Java type the given records is associated with. So, to get all records associated with the Ancestor class, you would perform a single query against the Ancestor table for records where the DTYPE is Ancestor, Parent or Child, as all share an is-a relationship with the Ancestor class. On the other hand, to find all records associated with Child instances, Hibernate would simply query the Ancestor table for records where the DTYPE is set to Child. Overall, this data access strategy tends to be fairly simple, fairly efficient, and the most manageable.

Single_Table_Type_Mapping_mysql_results_admin_gui_tools_parent_child_ancestor_with_hibernate_and_JPA_tutorial.gif

Looking at the database after running our main method, we can see three records, all differentiated by the DTYPE column, as being associated with either the Ancestor, Child or Parent class.


hibernate java hibernate spring hibernate hibernate cache hibernate class hibernate collection hibernate configuration hibernate database hibernate dialect hibernate download hibernate example hibernate mapping hibernate query hibernate sql hibernate tutorial hibernate xml struts hibernate xp hibernate 3 hibernate 3.0 hibernate api hibernate caching hibernate cfg xml hibernate dao hibernate examples hibernate framework hibernate generator hibernate in action hibernate jdbc hibernate list hibernate one to one hibernate plugin hibernate properties hibernate tool hibernate tools hibernate training hibernate tutorials java persistence with hibernate jboss hibernate linux hibernate standby hibernate ubuntu hibernate xdoclet hibernate hibernate synchronizer computer hibernate disable hibernate enable hibernate hibernate 2 hibernate 3.2 hibernate annotation hibernate annotations hibernate bag hibernate batch hibernate blob hibernate button hibernate c3p0 hibernate cascade hibernate command hibernate composite id hibernate composite key hibernate config hibernate connection hibernate criteria hibernate date hibernate delete hibernate discriminator hibernate documentation hibernate ehcache hibernate entitymanager hibernate enum hibernate fetch hibernate file hibernate filter hibernate flush hibernate formula hibernate forum hibernate hbm hibernate hbm2ddl hibernate hbm2ddl auto hibernate hql hibernate id hibernate in vista hibernate inheritance hibernate insert hibernate interceptor hibernate interview questions hibernate inverse hibernate javadoc hibernate join hibernate jpa hibernate lazy hibernate lazy loading hibernate load hibernate logging hibernate many to many hibernate many to one hibernate map hibernate mapping file hibernate merge hibernate mode hibernate named query hibernate order hibernate order by hibernate org hibernate performance hibernate problems hibernate property hibernate proxy hibernate query language hibernate reference hibernate restrictions hibernate reverse engineering hibernate save hibernate saveorupdate hibernate search hibernate select hibernate sequence hibernate session hibernate sessionfactory hibernate set hibernate shortcut hibernate show_sql hibernate source hibernate sql query hibernate stored procedure hibernate template hibernate timestamp hibernate transaction hibernate type hibernate update hibernate usertype hibernate validator hibernate version how to hibernate laptop hibernate net sf hibernate netbeans hibernate org hibernate dialect org hibernate session sleep hibernate sleep vs hibernate spring and hibernate standby vs hibernate turn off hibernate vista hibernate what is hibernate windows hibernate windows xp hibernate all 150 Help java spring apache xml ajax cache cmp j2ee s truts tomcat ejb jboss jsf maven primary key ruby on rails foreign key hibernation ibatis one to one spring framework xdoclet hql hybernate jdo many to many middlegen ojb one to many

eXTReMe Tracker