Hibernate - SPLessons
boy2 Chapter 19

Hibernate Hierarchy

Hibernate - SPLessons

Hibernate Hierarchy

shape Introduction

Hibernate Hierarchy table uses Annotations stores all Persistence class properties in one table. The Hibernate Hierarchy main advantage of using annotation is no need to write Hibernate mapping file. Table per hierarchy uses discriminator column in hibernate actually but here developer is using annotations so same will be used with annotation. Annotations like below has to be used for mapping table as per hierarchy strategy.

 

shape Conceptual
figure

Following is an example Inheritance hierarchy shown below. Where created one base class(payment) and base class has two derived classes(credit card, debit card).


shape Table

The table structure for this hierarchy

Table Per Hierarchy

shape Example

An Example of Table Per Hierarchy by using Annotations.

  • Create the persistence classes and configuration file and also Create the class to stores the data..
    Project Structure.
  • Create the Persistance classes.

Payment.java

package com.itoolsinfo;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;

@Entity
@Table(name="SalaryDetails")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="paymentmode")
@DiscriminatorValue(value="employee")
public class Payment 
{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
	private int paymentId;
    @Column(name="amount")
    private double amount;
	public int getPaymentId() {
		return paymentId;
	}
	public void setPaymentId(int paymentId) {
		this.paymentId = paymentId;
	}
	public double getAmount() {
		return amount;
	}
	public void setAmount(double amount) {
		this.amount = amount;
	}
}

Discriminator is commonly used in SINGLE_TABLE inheritance because one can need a column to identify the type of the record. Every element bean will have an essential key, which you comment on the class with the @Id annotation. The essential key can be a solitary field or a mix of different fields relying upon your table structure.

As a matter of course, the @Id annotation will naturally decide the most suitable essential key era technique to be utilized however you can abrogate this by applying the @GeneratedValue explanation which takes two parameters system and generator.
CreditCard.java

package com.itoolsinfo;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue("creditcard")
public class CreditCard extends Payment
{
@Column(name="cardNumber")
private int cardNumber;
@Column(name="cardType")
private String cardType;
public int getCardNumber() {
return cardNumber;
}
public void setCardNumber(int cardNumber) {
this.cardNumber = cardNumber;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}

}

The @Column annotation is utilized to indicate the points of interest of the segment to which a field or property will be mapped.
DebitCard.java

package com.itoolsinfo;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue("debitcard")
public class DebitCard extends Payment
{
	    @Column(name="pinNumber")
        private int pinNumber;
	    @Column(name="cardName")
        private String cardName;
		public int getPinNumber() {
			return pinNumber;
		}
		public void setPinNumber(int pinNumber) {
			this.pinNumber = pinNumber;
		}
		public String getCardName() {
			return cardName;
		}
		public void setCardName(String cardName) {
			this.cardName = cardName;
		}
}		

The @Column explanation is utilized to indicate the points of interest of the segment to which a field or property will be mapped.

  • Add the persistance classes in configuration file.

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  
<hibernate-configuration>  
  
    <session-factory>
    
        <property name="hibernate.hbm2ddl.auto">create</property>  
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>  
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <!-- property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property--> 
        <property name="connection.username">system</property>  
        <property name="connection.password">system</property>  
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>  
   		
   		 <mapping class="com.iquickinfo.Payment"/>
   		 <mapping class="com.iquickinfo.CreditCard"/> 
   		  <mapping class="com.iquickinfo.DebitCard"/> 
   		  
    </session-factory>  
  </hibernate-configuration>  
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
  • Create the SPLessons class and stores the POJO Class objects.

SPLessons.java

package com.itoolsnfo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class SPLessons
{
	public static void main(String args[])
	{   
		SessionFactory factory=new Configuration().configure().buildSessionFactory();
		 Session session=factory.openSession();
		
		     Payment payment=new Payment();
		         payment.setPaymentId(3);
		         payment.setAmount(20000);
			
		      CreditCard creditcard=new CreditCard();
			    creditcard.setCardNumber(5678);
			    creditcard.setCardType("visa");
			    
			  DebitCard debitcard=new DebitCard();
			   debitcard.setPinNumber(6785);
			   debitcard.setCardName("KARUR VYSYA BANK");
			   
                     Transaction transaction=session.beginTransaction();
			 
			        session.save(payment);
			        session.save(creditcard);
				 session.save(debitcard);
				  transaction.commit();
				    session.close();
              System.out.println("Payment datails all are entered using annotations");
	}   
}		      

Database operations will be performed here.
Output:
Now check the database, result will be as follows.

Summary

shape Key Points

  • Hibernate Hierarchy – If developer use annotations then do not need to use hibernate mapping file
  • Hibernate Hierarchy – In Hibernate table per hierarchy base class object and derived class object will be stored in a single table.