Monday, December 9, 2013

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:

@Entity
@Table(name = "USER") 
@Inheritance(strategy=InheritanceType.JOINED)  
public class User implements Serializable{
     @Id    
     @Column(name = "USER_ID")
     private String userId;
     
     @Column(name = "USERNAME")
     private String userName;
     
     @Column(name = "PASSWORD")
     private String password;
     
     //setters and getters
}

Customer Class:

@Entity
@Table(name="CUSTOMER") 
@PrimaryKeyJoinColumn(name="USER_ID") 

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:

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

Note:
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.

                                                Continued...

No comments:

Post a Comment