0% found this document useful (0 votes)
71 views5 pages

Hibernate Table Per Hierarchy Using Annotation

This document provides an example of mapping an object inheritance hierarchy to a single database table using Hibernate annotations. It defines 3 classes - Employee, RegularEmployee, and ContractEmployee mapped to a single "employee101" table. The table contains a "type" discriminator column to identify the subclass. The example creates the entity classes with JPA annotations, configures Hibernate in pom.xml and hibernate.cfg.xml, and demonstrates persisting objects to the database in a StoreTest class.

Uploaded by

Akanksha Bhagia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
71 views5 pages

Hibernate Table Per Hierarchy Using Annotation

This document provides an example of mapping an object inheritance hierarchy to a single database table using Hibernate annotations. It defines 3 classes - Employee, RegularEmployee, and ContractEmployee mapped to a single "employee101" table. The table contains a "type" discriminator column to identify the subclass. The example creates the entity classes with JPA annotations, configures Hibernate in pom.xml and hibernate.cfg.xml, and demonstrates persisting objects to the database in a StoreTest class.

Uploaded by

Akanksha Bhagia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 5

Hibernate Table Per Hierarchy using Annotation

In the previous page, we have mapped the inheritance hierarchy with one table using xml file. Here, we are going to perform this task
using annotation. You need to use @Inheritance(strategy=InheritanceType.SINGLE_TABLE), @DiscriminatorColumn and
@DiscriminatorValue annotations for mapping table per hierarchy strategy.

In case of table per hierarchy, only one table is required to map the inheritance hierarchy. Here, an extra column (also known
as discriminator column) is created in the table to identify the class.

Let's see the inheritance hierarchy:

Example of Hibernate Table Per Hierarchy using Annotation

You need to follow the following steps to create simple example:

o Create the persistent classes


o Edit pom.xml file
o Create the configuration file
o Create the class to store the fetch the data

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

package com.javatpoint.mypackage;  
import javax.persistence.*;  
  
@Entity  
@Table(name = "employee101")  
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)  
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)  
@DiscriminatorValue(value="employee")  
  
public class Employee {  
@Id  
@GeneratedValue(strategy=GenerationType.AUTO)  
      
@Column(name = "id")  
private int id;  
  
@Column(name = "name")  
private String name;  
  
//setters and getters  
}  

File: Regular_Employee.java

package com.javatpoint.mypackage;  
  
import javax.persistence.*;  
  
@Entity  
@DiscriminatorValue("regularemployee")  
public class Regular_Employee extends Employee{  
      
@Column(name="salary")    
private float salary;  
  
@Column(name="bonus")     
private int bonus;  
  
//setters and getters  
}  
File: Contract_Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. import javax.persistence.Column;  
4. import javax.persistence.DiscriminatorValue;  
5. import javax.persistence.Entity;  
6.   
7. @Entity  
8. @DiscriminatorValue("contractemployee")  
9. public class Contract_Employee extends Employee{  
10.       
11.     @Column(name="pay_per_hour")  
12.     private float pay_per_hour;  
13.       
14.     @Column(name="contract_duration")  
15.     private String contract_duration;  
16.   
17.     //setters and getters  
18. }  

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) Add the persistent classes in configuration file


Open the hibernate.cgf.xml file, and add entries of entity classes like this:

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

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

4) Create the class that stores the persistent object

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

File: StoreTest.java

1. package com.javatpoint.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 StoreTest {  
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. }  

Output:

You might also like