Pages Navigation Menu

Coding is much easier than you think

Table per Class Hierarchy Example using XML

Posted by on Apr 9, 2015 in Hibernate | 0 comments

Table per class hierarchy
 
In our previous tutorial we got introduced to Inheritance Mapping In Hibernate, In this article I will explain you about Table per Class Hierarchy Inheritance mapping. By this inheritance strategy, we can map the whole hierarchy in a single table. Here, an extra column otherwise known as discriminator column is created in the table to identify the class. In the table, for each record some columns will be empty; those columns for which the particular Java class does not have fields.
 
Inheritance
 
The above is the Hierarchy of classes involved. Here Employee is the super class for PermanentEmployee and ContractEmployee classes. Now Let us create Java classes for the above hierarchy to implement
 

Model class

 
File: Employee.java

package model;

public class Employee {
	private int empID;
	private String empName;

	public int getEmpID() {
		return empID;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpID(int empID) {
		this.empID = empID;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

}

 
File: PermanentEmployee.java

package model;

public class PermanentEmployee extends Employee {
	private String companyName;

	public String getCompanyName() {
		return companyName;
	}

	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}

}

 
File: ContractEmployee.java

package model;

public class ContractEmployee extends Employee {
	String contractorName;

	public String getContractorName() {
		return contractorName;
	}

	public void setContractorName(String contractorName) {
		this.contractorName = contractorName;
	}
}

 

Hibernate Mapping xml

 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="model.Employee" discriminator-value="Employee"
		table="EMPLOYEE">
		<id name="empID" type="int" column="EMPID">
			<generator class="assigned" />
		</id>
		<discriminator column="DTYPE" type="string" />
		<property name="empName" type="java.lang.String" column="EMP_NAME" />

		<subclass name="model.PermanentEmployee" discriminator-value="Permanent employee">
			<property name="companyName" column="COMPANY_NAME" />
		</subclass>
		<subclass name="model.ContractEmployee" discriminator-value="Contract Employee">
			<property name="contractorName" column="CONTRACTOR_NAME" />
		</subclass>

	</class>
</hibernate-mapping>

 
In case of table per class hierarchy a discriminator column is added by the hibernate framework that specifies the type of the record. It is mainly used to identify which derived class object have been saved in the table (see Database screen shot for better understanding). To specify this, discriminator sub element (Line no 10) of class must be specified.
 
The subclass sub element of class, specifies the subclass. In this case, PermanentEmployee and ContractEmployee are the subclasses of Employee class.
 

Hibernate Configuration file

 

<hibernate-configuration>

	<session-factory>
		<!-- Database connection settings -->
		<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="hibernate.connection.username">system</property>
		<property name="hibernate.connection.password">admin</property>
		<property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property>

		<!-- JDBC connection pool (use the built-in) -->
		<property name="connection.pool_size">2</property>

		<!-- SQL dialect -->
		<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>

		<!-- Enable Hibernate's current session context -->
		<property name="current_session_context_class">thread</property>

		<!-- Disable the second-level cache -->
		<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

		<!-- Echo all executed SQL to sysout -->
		<property name="show_sql">true</property>

		<!-- Drop and re-create the database schema on startup -->
		<property name="hibernate.hbm2ddl.auto">create</property>
		<mapping resource="Employee.hbm.xml" />

	</session-factory>

</hibernate-configuration>

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

Client program

 
Create the class that stores the persistent object in this class, we are simply storing the employee objects in the database.
 

package util;

import model.ContractEmployee;
import model.PermanentEmployee;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

	public static void main(String[] args) {

		Configuration cf = new Configuration().configure("hibernate.cfg.xml");

		StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
		srb.applySettings(cf.getProperties());
		ServiceRegistry sr = srb.build();
		SessionFactory sf = cf.buildSessionFactory(sr);

		Session session = sf.openSession();

		PermanentEmployee p1 = new PermanentEmployee();
		p1.setEmpID(1);
		p1.setEmpName("Ameer");
		p1.setCompanyName("CTS");

		PermanentEmployee p2 = new PermanentEmployee();
		p2.setEmpID(2);
		p2.setEmpName("Lourde");
		p2.setCompanyName("TCS");

		// create two objects of ContractEmployee
		ContractEmployee t1 = new ContractEmployee();
		t1.setEmpID(3);
		t1.setEmpName("Prabhu");
		t1.setContractorName("ABD Consultancy");

		ContractEmployee t2 = new ContractEmployee();
		t2.setEmpID(4);
		t2.setEmpName("Badru");
		t2.setContractorName("MN Consultancy");

		Transaction tx = session.beginTransaction();

		session.save(p1);
		session.save(p2);
		session.save(t1);
		session.save(t2);

		tx.commit();
		System.out.println("Object saved successfully !");
		session.close();
		sf.close();
	}
}

 

Eclipse Console

 
eclipse console

Database output

 
table-per-class

Read More

Introduction to Inheritance Mapping In Hibernate

Posted by on Apr 8, 2015 in Hibernate | 0 comments

Inheritance Mapping
 
Java, being a OOPs language, supports inheritance for reusability of classes. Hibernate comes with a provision to create tables and populate them as per the Java classes involved in inheritance. Suppose if we have base and derived classes, now if we save derived class object, then base class object too will be stored into the database. In order to do so, you need to choose certain mapping strategy based on your needs to save objects.
 
Hibernate supports 3 types of Inheritance Mappings to map classes involved in inheritance with database tables.
 
Example:
 
Inheritance
In the above hierarchy, three classes are involved where Employee is the super class and PermanentEmployee and ContractEmployee are subclasses.
 
Now the question is how many tables are required and how to link the tables so that PermanentEmployee gets three properties of empId and empName (from super class), companyName.
 

The three approaches adopted by Hibernate

  • Table-per-class-hierarchy: Only one table is created for all the classes involved in hierarchy. Here we maintain an extra discriminator column in table to differentiate between PermanentEmployee and ContractEmployee.
     
    For table-per-class hierarchy we use <subclass> in hibernate mapping file to maintain the relation between super class and subclass.
     
    Example:
     
    table-per-class
     
  • Table-per-subclass: One table for each class is created. The above hierarchy creates three tables like following where super class primary key is subclass foreign key.
     
    For table-per-subclass we use <joined- subclass> in hibernate mapping file to maintain the relation between super class and subclass.
     
    Example:
     
    Employee
     
    P_EMPLOYEE
     
    T_Employee
     
    PID and TID are the foreign keys for EMPID of super class. This relation will be given in the mapping file.
  •  

  • Table-per-concrete-class: One table for each concrete class (subclass) is created but not of super class. Here, foreign key is not maintained.
     
    For table-per-concrete-class we use <union-subclass> in hibernate mapping file to maintain the relation between super class and subclass.
     
    P_EMPLOYEE2
     
    T_Employee2

 
In our upcoming articles we shall explore each of the above mapping in detail
 

Annotation mapping

1. Table per Class Hierarchy Using Annotation
2. Table per Subclass Using Annotation
3. Table per Concrete class Using Annotation
 

XML mapping

1. Table per Class Hierarchy using XML Mapping
2. Table per Subclass using XML Mapping
3. Table per Concrete class using XML Mapping
 

Read More

Hibernate update query example

Posted by on Mar 20, 2015 in Hibernate, Hibernate Annotation | 0 comments

Update Query
 
In previous article we learnt to implement Hibernate delete Query example in Eclipse, in this article I will implement a program to update an object which is already persisted in the database.
 

Project Structure

 
HibernateHelloWorld
 

Entity class

 

package entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "STUDENT")
public class StudentEntity {

	@Id
	@Column(name = "ID")
	private int id;
	
	@Column(name = "NAME")
	private String name;
	
	@Column(name = "DEPARTMENT")
	private String department;
	
	@Column(name = "COLLEGE")
	private String college;

// Create Getters and Setters
}

 
Note: I have explained about every annotations used in the above file in the article Generic Hibernate Application Requirements
 

Hibernate Configuration file

 
File: hibernate.cfg.xml

<hibernate-configuration>

<session-factory>
   <!-- Database connection settings -->
   <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
   <property name="hibernate.connection.username">system</property>
   <property name="hibernate.connection.password">admin</property>
   <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property>

   <!-- SQL dialect -->
   <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

   <!-- Echo all executed SQL to sysout -->
   <property name="show_sql">true</property>

   <!-- Create/Update the database schema on startup -->
   <property name="hibernate.hbm2ddl.auto">update</property>
   <!-- Mapping file -->
   <mapping resource="Student.hbm.xml" />

</session-factory>

</hibernate-configuration>

 

Hibernate Utility

 

package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import model.Student;

public class HibernateUtil {

	public static void main(String[] args) {

		Configuration cf = new Configuration().configure("hibernate.cfg.xml");

		StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
		srb.applySettings(cf.getProperties());
		ServiceRegistry sr = srb.build();
		SessionFactory sf = cf.buildSessionFactory(sr);

		Session session = sf.openSession();

		Student std = (Student) session.load(Student.class, new Integer(2));
		Transaction tx = session.beginTransaction();

		// std.setId(3); // We Should not update "id"
		std.setName("Ameer");
		std.setCollege("PSG");
		tx.commit(); // Update method will be called implicitly.
		System.out.println("Object Updated successfully !");
		session.close();
		sf.close();
	}
}

 

Hibernate Cache

  • Whenever an object is loaded from database, hibernate stores the loaded object in cache memory which works in session scope.
  • Now if we do any modifications to the loaded object, then these modification are stored only in the object maintained by cache memory. Even if we modify the loaded object for multiple times then also the modifications will be stored only in the cached object.
  • But once we call transactions commit() method then hibernate will check whether there are any changes between the object present in the database and the object stored in the cache, now the if changes exists then hibernate will automatically call its update method internally and updates the student object in database.

 

Program Explanation

  • Line no 28: We should not update id, because we have loaded the object from the database only using this id member variable (See line no 25). So if we update this field, then hibernate will throws NonUniqueObjectException.
  • At line no 29, I have updated name property of student object.
  • Line no 31: So once commit() method is triggered from program, then hibernate will automatically call update method internally and updates the student object.

 

Data in DB before running the program

 
Hibernate DB
 

Run it – Eclipse Console

 
Hibernate Update
 

Data in DB after running the program

 
Update DB
 

Read More

Hibernate Delete Query example

Posted by on Mar 16, 2015 in Hibernate, Hibernate Annotation | 0 comments

Hibernate Delete Query
 
In previous article we learnt to implement Hibernate Select Query example in Eclipse, In this article I will implement an example on delete the object from the database(Delete Query) using Hibernate.
 

Project Structure

 
HibernateHelloWorld
 

Entity class

 

package entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "STUDENT")
public class StudentEntity {

	@Id
	@Column(name = "ID")
	private int id;
	
	@Column(name = "NAME")
	private String name;
	
	@Column(name = "DEPARTMENT")
	private String department;
	
	@Column(name = "COLLEGE")
	private String college;

// Create Getters and Setters
}

 
Note: I have explained about every annotations used in the above file in the article Generic Hibernate Application Requirements
 

Hibernate Configuration file

 
Create a new XML file and give this new configuration file the default name hibernate.cfg.xml and place it src directory of your project.
 
File: hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
	<!-- Database connection settings -->
	<property name="hibernate.connection.driver_class">
                  oracle.jdbc.driver.OracleDriver
        </property>
	<property name="hibernate.connection.username">system</property>
	<property name="hibernate.connection.password">admin</property>
	<property name="hibernate.connection.url">
                   jdbc:oracle:thin:@xxx.x.x.x:1521:XE
        </property>

	<!-- SQL dialect -->
	<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

	<!-- Echo all executed SQL to sysout -->
	<property name="show_sql">true</property>

	<!-- Drop and re-create the database schema on startup -->
	<property name="hibernate.hbm2ddl.auto">update</property>
	<!-- Map Entity Class -->
    <mapping class="entity.StudentEntity"></mapping>

</session-factory>
</hibernate-configuration>

 

Hibernate Utility

 

package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import entity.StudentEntity;

public class HibernateUtil {

	public static void main(String[] args) {

		Configuration cf = new Configuration().configure("hibernate.cfg.xml");

		StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
		srb.applySettings(cf.getProperties());
		ServiceRegistry sr = srb.build();
		SessionFactory sf = cf.buildSessionFactory(sr);

		Session session = sf.openSession();
		StudentEntity std = (StudentEntity) session.load(StudentEntity.class, new Integer(2));
		Transaction tx = session.beginTransaction();
		session.delete(std);
		tx.commit();
		System.out.println("Object Deleted successfully !");
		session.close();
		sf.close();
	}
}

 
In the above program we are deleting an object, which is already persisted (inserted) in the database; So in order to delete an persisted object, we need to load that object from the database and pass that object to the delete() method of Session interface, now hibernate delete that object whenever the transaction is committed.
 
In the article Steps to be followed to use Hibernate in Java, I have explained the configuration/code used in above program in detail.
 

Data in DB before running the program

 
Hibernate DB
 

Run it – Eclipse Console

 
Hibernate Delete
 

Data in DB after running the program

 
Delete after
 

Read More

Hibernate Select Query

Posted by on Mar 15, 2015 in Hibernate, Hibernate Annotation | 0 comments

Hibernate Select Query
 
In previous article we learnt to implement Hibernate 4 Insert Query example in Eclipse, In this article I will implement an example on loading the object from the database(Select Query) using Hibernate.
 

Project Structure

 
HibernateHelloWorld
 

Entity class

 

package entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "STUDENT")
public class StudentEntity {

	@Id
	@Column(name = "ID")
	private int id;
	
	@Column(name = "NAME")
	private String name;
	
	@Column(name = "DEPARTMENT")
	private String department;
	
	@Column(name = "COLLEGE")
	private String college;

// Create Getters and Setters
}

 
Note: I have explained about every annotations used in the above file in the article Generic Hibernate Application Requirements
 

Hibernate Configuration file

 
Create a new XML file and give this new configuration file the default name hibernate.cfg.xml and place it src directory of your project.
 
File: hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
	<!-- Database connection settings -->
	<property name="hibernate.connection.driver_class">
                  oracle.jdbc.driver.OracleDriver
        </property>
	<property name="hibernate.connection.username">system</property>
	<property name="hibernate.connection.password">admin</property>
	<property name="hibernate.connection.url">
                   jdbc:oracle:thin:@xxx.x.x.x:1521:XE
        </property>

	<!-- SQL dialect -->
	<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

	<!-- Echo all executed SQL to sysout -->
	<property name="show_sql">true</property>

	<!-- Drop and re-create the database schema on startup -->
	<property name="hibernate.hbm2ddl.auto">update</property>
	<!-- Map Entity Class -->
    <mapping class="entity.StudentEntity"></mapping>

</session-factory>
</hibernate-configuration>

 

Hibernate Utility

 

package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import entity.StudentEntity;

public class HibernateUtil {

   public static void main(String[] args) {

     Configuration cf = new Configuration().configure("hibernate.cfg.xml");
 
     StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
     srb.applySettings(cf.getProperties());
     ServiceRegistry sr = srb.build();
     SessionFactory sf = cf.buildSessionFactory(sr);

     Session session = sf.openSession();
     StudentEntity std = (StudentEntity) session.load(StudentEntity.class, new Integer(1));

     // For loading Transaction object is not necessary
     System.out.println("Loaded object Student name is: " + std.getName());

     System.out.println("Object Loaded successfully.....!!");
     session.close();
     sf.close();
     }
}

 
In the article Steps to be followed to use Hibernate in Java, I have explained the configuration/code used in above program in detail.
 

Data in Database

 
Hibernate DB
 

Run it – Eclipse Console

 
Hibernate Select Query
 

Note

 
In hibernate we have 2 methods to load the object from the database, they are get and load. To know the difference between get and load method read the article here.
 

Read More

Hibernate 4 Hello World example in Eclipse using XML Mapping

Posted by on Mar 15, 2015 in Hibernate, Hibernate XML Mapping | 0 comments

Hibernate Hello world
 
This is the 4th article on Hibernate in java application that describes on how to to save an object from java into the database using Hibernate 4(Hibernate 4 Insert Query). If you have not read my previous articles article on Generic Hibernate Application Requirements (XML Mapping) and Steps to be followed to use Hibernate in Java, I will recommend that you read that article first. You may want to look at Hibernate Installation/Setup on Eclipse IDE article if Hibernate is not installed already on your system.
 
As described earlier, the following files are the minimum requirement to shape an hibernate program..

Student.java (Model class)
Student.hbm.xml  (Xml mapping file )
hibernate.cfg.xml  (Xml configuration file)
HibernateUtil.java (Main class to write hibernate logic)

 

Project Structure


 
The final appearance of the application should be as follows:
 
HibernateHelloWorld
 

Model class

 
Example:Student.java
 

package model;

public class Student {
	private int id;
	private String name;
	private String department;
	private String college;

// Create Getters and Setters
}

 

Hibernate Mapping file for Model Class

 
Now Create a new XML file(Student.hbm.xml) which is our mapping file related to above model class and place it in the src directory of your project.
 
Student.hbm.xml : A simple hibernate XML mapping
 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="model.Student" table="STUDENT">
		<id name="id" column="STUDENT_ID">
			<generator class="assigned" />
		</id>
		<property name="name" column="STUDENT_NAME" />
		<property name="department" />
		<property name="college" />
	</class>
</hibernate-mapping>

 
Note: I have explained about each and every element used in the above file in the article Generic Hibernate Application Requirements
 

Hibernate Configuration file

 
Create a new XML file and give this new configuration file the default name hibernate.cfg.xml and place it src directory of your project.
 
File: hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
   <!-- Database connection settings -->
   <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
   <property name="hibernate.connection.username">system</property>
   <property name="hibernate.connection.password">admin</property>
   <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property>

   <!-- SQL dialect -->
   <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

   <!-- Echo all executed SQL to sysout -->
   <property name="show_sql">true</property>

   <!-- Drop and re-create the database schema on startup -->
   <property name="hibernate.hbm2ddl.auto">create</property>
   <!-- Mapping file -->
   <mapping resource="Student.hbm.xml" />

</session-factory>

</hibernate-configuration>

 

Hibernate Utility

 
Create the Main class to run the example.
 

package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import model.Student;

public class HibernateUtil {

	public static void main(String[] args) {

		Configuration cf = new Configuration().configure("hibernate.cfg.xml");

		StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
		srb.applySettings(cf.getProperties());
		ServiceRegistry sr = srb.build();
		SessionFactory sf = cf.buildSessionFactory(sr);

		Session session = sf.openSession();
		Student std = new Student();
		std.setId(1);
		std.setName("Jamil");
		std.setDepartment("ECE");
		std.setCollege("SKCET");

		Transaction tx = session.beginTransaction();
		session.save(std);
		tx.commit();
		System.out.println("Object saved successfully.....!!");
		session.close();
		sf.close();
	}
}

 
In the article Steps to be followed to use Hibernate in Java, I have explained the configuration/code used in above program in detail.
 
Now once our project is ready. Right click to project or right click to HibernateUtil.java and click Run As–>Java Application. Since I have set show_sql to true in hibernate.cfg.xml, so the hibernate create and insert quires will be displayed on eclipse console as below.
 
Hibernate Console
 
You will see the data stored in Student table in the database.
 
Hibernate Result
 
In my next article I have implemented Select Query in Hibernate
 
download

Read More