Hibernate Tutorial - Part V

For previous posts, refer:
Hibernate tutorial Part - I
Hibernate tutorial Part - II
Hibernate tutorial Part - III

Hibernate tutorial Part - IV

In this post, we are going to take a look at ' Table per subclass' approach for inheritance.

Table per subclass:

This strategy, represents inheritance relationships as relational foreign key associations.Every class/subclass that declares persistent properties, including abstract classes and even interfaces has its own table.

Unlike the table per concrete class strategy, the table here contains columns only for each non inherited property (each property declared by the subclass itself) along with a primary key that is also a foreign key of the super class table.

Lets take a look at the class definitions and annotations:

User Class:

@Table(name = "USER") 
public class User implements Serializable{
     @Column(name = "USER_ID")
     private String userId;
     @Column(name = "USERNAME")
     private String userName;
     @Column(name = "PASSWORD")
     private String password;
     //setters and getters

Customer Class:


public class Customer extends User implements Serializable{
     @Column(name = "ADDRESS1")
     private String address1;
     @Column(name = "ADDRESS2")
     private String address2;
     @Column(name = "CITY")
     private String city;
     @Column(name = "STATE")
     private String state;
     @Column(name = "COUNTRY")
     private String country;
     //setters and getters

InternalUser Class:

@Table(name = "INTERNAL_USER") 
public class InternalUser extends User implements Serializable{
     /*Admin/Non Admin*/
     @Column(name = "ACCESSTYPE")
     private String accessType;
     @Column(name = "EMPLOYMENTTYPE")
     private String employmentType;
     //setters and getters

1. For every record for subclass, there will be a record in USER table as well. For eg, if we save Customer and InternalUser, then there will be one record each in INTERNAL_USER AND CUSTOMER and two records in USER.
2. Hibernate uses outer join to query subclass data

Disadvantage of this approach:

Involves a number of joins to join child tables. This could cause issues when there is a huge hierarchy with lot of subclasses.



Popular posts from this blog

Pivotal Cloud Foundry (PCF) Integration with Elastic Cloud Storage (ECS)

Restful code example using Spring MVC

Spring Integration - Bulk processing Example