Hibernate Table per subclass using annotation tutorial

As we have indicated before, if there should be an occurrence of table for each subclass system, tables are made according to determined classes yet they are dealt with utilizing essential and outside key. So there won't be any copy segment in the relation.

We need to determine @Inheritance(strategy=InheritanceType.JOINED) in the parent class and @PrimaryKeyJoinColumn comment in the subclasses.

Let's see the order of classes that we are going to map.

table per subclass strategy

The table structure for each table will be as follows:

In this example we are creating the three classes and provide mapping of these classes in the employee.hbm.xml file.

1) Create the Persistent classes

You need to create the persistent classes representing the inheritance. Let's create the three classes for the above hierarchy:

File: Employee.java
  1. package com.javacodegeeks.mypackage;  
  2. import javax.persistence.*;  
  3.   
  4. @Entity  
  5. @Table(name = "employee103")  
  6. @Inheritance(strategy=InheritanceType.JOINED)  
  7.   
  8. public class Employee {  
  9. @Id  
  10. @GeneratedValue(strategy=GenerationType.AUTO)  
  11.       
  12. @Column(name = "id")  
  13. private int id;  
  14.   
  15. @Column(name = "name")  
  16. private String name;  
  17.   
  18. //setters and getters  
  19. }  
File: Regular_Employee.java
  1. package com.javacodegeeks.mypackage;  
  2.   
  3. import javax.persistence.*;  
  4.   
  5. @Entity  
  6. @Table(name="regularemployee103")  
  7. @PrimaryKeyJoinColumn(name="ID")  
  8. public class Regular_Employee extends Employee{  
  9.       
  10. @Column(name="salary")    
  11. private float salary;  
  12.   
  13. @Column(name="bonus")     
  14. private int bonus;  
  15.   
  16. //setters and getters  
  17. }  
File: Contract_Employee.java
  1. package com.javacodegeeks.mypackage;  
  2.   
  3. import javax.persistence.*;  
  4.   
  5. @Entity  
  6. @Table(name="contractemployee103")  
  7. @PrimaryKeyJoinColumn(name="ID")  
  8. public class Contract_Employee extends Employee{  
  9.       
  10.     @Column(name="pay_per_hour")  
  11.     private float pay_per_hour;  
  12.       
  13.     @Column(name="contract_duration")  
  14.     private String contract_duration;  
  15.   
  16.     //setters and getters  
  17. }  

2) Add project information and configuration in pom.xml file.

Open pom.xml file and click source. Now, add the below dependencies between <dependencies>....</dependencies> tag.

  1. <dependency>  
  2.     <groupId>org.hibernate</groupId>  
  3.     <artifactId>hibernate-core</artifactId>  
  4.     <version>5.3.1.Final</version>  
  5. </dependency>  
  6.       
  7. <dependency>  
  8.     <groupId>com.oracle</groupId>  
  9.     <artifactId>ojdbc14</artifactId>  
  10.     <version>10.2.0.4.0</version>  
  11. </dependency>  

3)Create the configuration file

Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:

  1. <mapping class="com.javacodegeeks.mypackage.Employee"/>  
  2. <mapping class="com.javacodegeeks.mypackage.Contract_Employee"/>  
  3. <mapping class="com.javacodegeeks.mypackage.Regular_Employee"/>  

Now the configuration file will look like this:

File: hibernate.cfg.xml
  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
  5.   
  6. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
  7. <hibernate-configuration>  
  8.   
  9.     <session-factory>  
  10.         <property name="hbm2ddl.auto">update</property>  
  11.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
  12.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>  
  13.         <property name="connection.username">system</property>  
  14.         <property name="connection.password">jtp</property>  
  15. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>  
  16.           
  17.         <mapping class="com.javacodegeeks.mypackage.Employee"/>  
  18.         <mapping class="com.javacodegeeks.mypackage.Contract_Employee"/>  
  19.         <mapping class="com.javacodegeeks.mypackage.Regular_Employee"/>  
  20.     </session-factory>  
  21.   
  22. </hibernate-configuration>  

The hbm2ddl.auto property is defined for creating automatic table in the database.


3) Create the class that stores the persistent object

In this class, we are simply storing the employee objects in the database.

File: StoreData.java
  1. package com.javacodegeeks.mypackage;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.Transaction;  
  6. import org.hibernate.boot.Metadata;  
  7. import org.hibernate.boot.MetadataSources;  
  8. import org.hibernate.boot.registry.StandardServiceRegistry;  
  9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
  10.   
  11. public class StoreData {  
  12.   
  13.     public static void main(String args[])  
  14.     {  
  15.         StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
  16.         Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();  
  17.           
  18.         SessionFactory factory=meta.getSessionFactoryBuilder().build();  
  19.         Session session=factory.openSession();  
  20.           
  21.          Transaction t=session.beginTransaction();    
  22.             
  23.             Employee e1=new Employee();    
  24.             e1.setName("Gaurav Chawla");    
  25.                 
  26.             Regular_Employee e2=new Regular_Employee();    
  27.             e2.setName("Vivek Kumar");    
  28.             e2.setSalary(50000);    
  29.             e2.setBonus(5);    
  30.                 
  31.             Contract_Employee e3=new Contract_Employee();    
  32.             e3.setName("Arjun Kumar");    
  33.             e3.setPay_per_hour(1000);    
  34.             e3.setContract_duration("15 hours");    
  35.                 
  36.             session.persist(e1);    
  37.             session.persist(e2);    
  38.             session.persist(e3);    
  39.                 
  40.             t.commit();    
  41.             session.close();    
  42.             System.out.println("success");        
  43.     }  
  44. }   package com.javacodegeeks.mypackage; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class StoreData { public static void main(String args[]) { StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build(); SessionFactory factory=meta.getSessionFactoryBuilder().build(); Session session=factory.openSession(); Transaction t=session.beginTransaction(); Employee e1=new Employee(); e1.setName("Gaurav Chawla"); Regular_Employee e2=new Regular_Employee(); e2.setName("Vivek Kumar"); e2.setSalary(50000); e2.setBonus(5); Contract_Employee e3=new Contract_Employee(); e3.setName("Arjun Kumar"); e3.setPay_per_hour(1000); e3.setContract_duration("15 hours"); session.persist(e1); session.persist(e2); session.persist(e3); t.commit(); session.close(); System.out.println("success"); } }






javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition