Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, September 27, 2015

Lambda Expressions in Java 8

Lambda Expressions:
  • Lambda expression is an anonymous function without any declarations. 
  • Lambda Expression are useful to write shorthand code and hence saves the effort of writing lengthy code. 
  • It promotes developer productivity, better readable and reliable code.
  • Lambda expressions can be converted to functional interfaces.
  • Lambda expressions can access effectively final variables from the enclosing scope..
Syntax of Lambda expression:
(arguments) -> {body}

Example of Lambda expression:
public class LambdaExpressions
{
  public static void main(String[] args)
  {        
    // Old way
    Runnable runnable = new Runnable() {
        public void run() {
            System.out.println("With out using Lambda Expressions .... ");
        }
    };
    
    Thread thread = new Thread(runnable);    
    thread.start();
    
    // Using Lambda Expressions
    Runnable runnable2 = () -> { System.out.println("With using Lambda Expressions .... ");};
    
    Thread thread2 = new Thread(runnable2);    
    thread2.start();    
  }
}
Output:
With out using Lambda Expressions .... 
With using Lambda Expressions .... 
Lambda expression arguments can contain zero or more arguments.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");

new Thread(() -> { System.out.println("Empty arguments.");}) {      // empty arguments          
}.run();;
        
names.forEach(name -> System.out.println(name));            // one argument with out specifying data type 
names.forEach((name) -> System.out.println(name));          // one argument with out specifying data type
names.forEach((String name) -> System.out.println(name));   // one argument with specifying data type
Note: We can omit the datatype of the parameters in a lambda expression. And also we can omit the parentheses if there is only one parameter.

Lambda expression body can contain any number of statements or with out statement also.
If body contains more than one statement then curly braces is mandatory otherwise it is optional.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");
        
names.forEach(((name) -> System.out.println(name))); // with out braces
        
names.forEach((name) -> {                            // with braces 
    System.out.println(name);
    System.out.println("Hello Mr. "+name);          
});

Sunday, May 17, 2015

What are all the different ways to create an object in Java?

There are four ways to create a Object in Java. They are

1. Using new keyword - This is the most common way to create an object in java.
Example:
MyObject object = new MyObject();

2. Using Class.forName() - If we know the name of the class and if it has a public default constructor we can create an object in this way.
Example:
MyObject object = (MyObject) Class.forName("com.ranga.MyObject").newInstance();

3. Using clone() - The clone() can be used to create a copy of an existing object.
Example:
MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();

4. Using object deserialization - Object deserialization is nothing but creating an object from its serialized form.
Example:
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();

Writing our own Collection mechanism to Sort different objects in Java.

SortCollections.java
---------------------------------------
package com.ranga.collections;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortCollections<T> {

private List<T> collectionList;
private String sortingField = null;
private boolean isAscending = true;

public SortCollections(List<T> objectList, String sortField) {
this(objectList, sortField, true);
}

public SortCollections(List<T> collectionList, String sortField, boolean isAscending) {
super();
this.collectionList = collectionList;
this.sortingField = sortField;
this.isAscending = isAscending;
}

@SuppressWarnings("rawtypes")
public List<T> sort( final Class claz) {
final String sortingField = this.sortingField;
final Boolean isAscending = this.isAscending;

Collections.sort(this.collectionList, new Comparator<T>() {
@Override
public int compare(T object1, T object2) {
try {
Field sortField = claz.getDeclaredField(sortingField);
sortField.setAccessible(true);

Object value1 = sortField.get(object1);
Object value2 = sortField.get(object2);

if (value1 instanceof String && value2 instanceof String) { // String field
String string1 = (String) value1;
String string2 = (String) value2;
if (true == isAscending) {
return string1.compareTo(string2);
} else {
return string2.compareTo(string1);
}
} else { // Numeric field
Number number1 = (Number) value1;
Number number2 = (Number) value2;
if (true == isAscending) {
if (number1.floatValue() > number2.floatValue()) {
return 1;
} else {
return -1;
}
} else {
if (number2.floatValue() > number1.floatValue()) {
return 1;
} else {
return -1;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
return this.collectionList;
}
}

Employee.java
---------------------------------------
    package com.ranga.collections;
import java.io.Serializable;
public class Employee implements Serializable {

private int id;
private String name;
private int age;
private float salary;

public Employee() {
super();
}

public Employee(int id, String name, int age, float salary) {
super();
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public float getSalary() {
return salary;
}

public void setSalary(float salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age
+ ", salary=" + salary + "]";
}
}

Application.java
---------------------------------------
package com.ranga.collections;
import java.util.ArrayList;
import java.util.List;
public class Application {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee(1,"Ranga", 26, 25677 ));
employees.add(new Employee(2,"Raja", 50, 2577 ));
employees.add(new Employee(3,"Vasu", 20, 30677 ));
employees.add(new Employee(4,"Mani", 45, 45677 ));
employees.add(new Employee(5,"Yasu", 29, 67677 ));
employees.add(new Employee(6,"Vinod", 80, 5677 ));

System.out.println(employees);
List<Employee> employeeList = new SortCollections<Employee>(employees, "name", false).sort(Employee.class);
System.out.println(employeeList);

employeeList = new SortCollections<Employee>(employees, "salary").sort(Employee.class);
System.out.println(employeeList);
}
}

Sunday, May 3, 2015

Hibernate4 One-to-One Relationship Example Using Annotations

In this article we are going to create a project to implement step by step one-to-one association example using Annotations with Maven project.

OneToOne Relationship:
A one-to-one relationship occurs when one entity is related to exactly one occurrence in another entity. For example, we have a Employee and Address tables, Employee has its single Address and each Address belongs to unique Employee. 

We can associate entities through a one-to-one relationship using the @OneToOne annotation (javax.persistence.OneToOne).

There are three different ways to implement OneToOne Association. 
1. Either the associated entities share the same primary key values(Shared Primary Key association).
2. A foreign key is held by one of the entities (One-to-One foreign key association).
3. A association table is used to store the link between the 2 entities (Using a join table).

1) One-to-One association using shared primary keys:
A one to one shared primary key relationship would mean that a Employee table does not have a foreign key column to Address table, rather the Address table's primary key value is the same as Employee, and acts as a foreign key to the Employee table.

In order to use a one to one with a shared primary key, ids on both sides of the object need a @GeneratedValue. The owner can use a generic generator where it gets a fresh number every time, but the other side of the one to one needs a custom hibernate extension, which is from @GenericGenerator. In our example, Address will have the hibernate extension @GenericGenerator.
Employee.java

@Entity
@Table(name="Employee")
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="employeeId")
private long id;

@OneToOne(mappedBy="employee", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
private Address address;
    // some more properties
 
    public Employee() {
super();
}
// setters and getters
}
Address.java

@Entity
@Table(name="Address")
@GenericGenerator(name="employee-primarykey", strategy="foreign", parameters=@Parameter(name="property", value="employee"))
public class Address implements Serializable {
@Id
@Column(name="addressId")
@GeneratedValue(generator="employee-primarykey")
private long addressId;

// some other properties

@OneToOne
@PrimaryKeyJoinColumn
private Employee employee;

public Address() {
super();
}
// setters and getters
}

The @PrimaryKeyJoinColumn annotation does say that the primary key of the entity is used as the foreign key value to the associated entity.

Let us see the full example.

Tools and Technologies Used: 
1. Java 6 or Above Version 
2. Hibernate 4.3.7 Final 
3. MySQL5.6 
4. Maven 3.2.2 
5. Eclipse Luna
Project Structure: 
Step-1. Creating Database and Tables:
CREATE DATABASE `vara_softtech`;
use vara_softtech;

CREATE TABLE `employee` (
`employeeId` bigint(20) NOT NULL AUTO_INCREMENT,
`age` int(11) DEFAULT NULL,
`firstName` varchar(255) DEFAULT NULL,
`lastName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`employeeId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

CREATE TABLE `address` (
`addressId` bigint(20) NOT NULL,
`city` varchar(255) DEFAULT NULL,
`houseNo` varchar(255) DEFAULT NULL,
`street` varchar(255) DEFAULT NULL,
PRIMARY KEY (`addressId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step-2. Creating  Maven-Eclipse Project:
In Eclipse IDE, create a Maven project named Hibernate4_Association_Mapping with the above structure.
This project consists of the following files:
Hibernate Configuration file: hibernate.cfg.xml
POJO classes: Employee.java and Address.java
Util class: HibernateUtil.java
Client Program: Application.java
Maven project: pom.xml
Step-3. Adding the project dependencies into pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
<groupId>com.varasofttech</groupId>
<artifactId>Hibernate4_Association_Mapping</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Association Mapping</name>
<dependencies>

<!-- Hibernate framework -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>

<!-- My SQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>
</project>

Step-4. Creating the Hibernate Configuration file hibernate.cfg.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!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 Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///vara_softtech</property>
<property name="hibernate.connection.username">varasofttech</property>
<property name="hibernate.connection.password">varasofttech</property>

<!-- Dialect class -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

<!-- Hibernate specific -->
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>

<!-- OneToOne Mapping -->
<mapping class="com.varasofttech.onetoone.Address" />
<mapping class="com.varasofttech.onetoone.Employee" />
</session-factory>
</hibernate-configuration>
Step-5. Creating the Hibernate Helper class HibernateUtil.java:
package com.varasofttech.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/**
*
* @author Ranga Reddy
* @date Feb 24, 2015
* @version 1.0
* @description : HibernateUtil.java
*/

public class HibernateUtil {
private static SessionFactory sessionFactory = null;

public static SessionFactory getSessionFacoty() {
return buildSessionFactory();
}
private static SessionFactory buildSessionFactory() {
if (sessionFactory == null) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();

sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
    public static void closeSessionFactory() {
if (sessionFactory != null)
sessionFactory.close();
            sessionFactory = null;
} }
Step-6. Creating the POJO classes Employee.java and Address.java:
package com.varasofttech.onetoone;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

/**
* @author Ranga Reddy
* @date Apr 20, 2015
* @version 1.0
* @description : Employee.java
*/


@Entity
@Table(name="Employee")
public class Employee implements Serializable {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="employeeId")
private long id;
@Column
private String firstName;
@Column
private String lastName;
@Column
private int age;

@OneToOne(mappedBy="employee", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
private Address address;

public Employee() {
super();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}

@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName
+ ", lastName=" + lastName + ", age=" + age + "]";
}
}
package com.varasofttech.onetoone;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.GenericGenerator;
/**
* @author Ranga Reddy
* @date Apr 20, 2015
* @version 1.0
* @description : Address.java
*/

@Entity
@Table(name="Address")
@GenericGenerator(name="employee-primarykey", strategy="foreign", parameters=@Parameter(name="property", value="employee"))
public class Address implements Serializable {

@Id
@Column(name="addressId")
@GeneratedValue(generator="employee-primarykey")
private long addressId;
@Column
private String houseNo;
@Column
private String street;
@Column
private String city;

@OneToOne
@PrimaryKeyJoinColumn
private Employee employee;

public Address() {
super();
}
public long getAddressId() {
return addressId;
}
public void setAddressId(long addressId) {
this.addressId = addressId;
}
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}

public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
@Override
public String toString() {
return "Address [addressId=" + addressId + ", houseNo=" + houseNo
+ ", street=" + street + ", city=" + city + "]";
}
}
Step-7. Creating the Client Application Application.java:
package com.varasofttech.onetoone;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.varasofttech.util.HibernateUtil;

/**
* @author Ranga Reddy
* @date Apr 20, 2015
* @version 1.0
* @description : Application.java
*/

public class Application {
public static void main(String[] args) {
Employee employee = new Employee();
employee.setFirstName("Ranga");
employee.setLastName("Reddy");
employee.setAge(27);

Address address = new Address();
address.setCity("Bangalore");
address.setHouseNo("12345");
address.setStreet("SRI Nagar");

employee.setAddress(address);
address.setEmployee(employee);

SessionFactory sessionFactory = HibernateUtil.getSessionFacoty();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
long employeeId = (Long) session.save(employee);

transaction.commit();
session.close();

sessionFactory = HibernateUtil.getSessionFacoty();
session = sessionFactory.openSession();
Employee emp = (Employee) session.get(Employee.class, employeeId);
System.out.println("Employee Details :");
System.out.println(emp);

System.out.println("Employee Address Details :");
System.out.println(emp.getAddress());
session.close();
}
}
Step-8. Run the client application
Hibernate: insert into Employee (age, firstName, lastName) values (?, ?, ?)
Hibernate: insert into Address (city, houseNo, street, addressId) values (?, ?, ?, ?)
Hibernate: select employee0_.employeeId as employee1_1_0_, employee0_.age as age2_1_0_, employee0_.firstName as firstNam3_1_0_, employee0_.lastName as lastName4_1_0_ from Employee employee0_ where employee0_.employeeId=?
Hibernate: select address0_.addressId as addressI1_0_0_, address0_.city as city2_0_0_, address0_.houseNo as houseNo3_0_0_, address0_.street as street4_0_0_, employee1_.employeeId as employee1_1_1_, employee1_.age as age2_1_1_, employee1_.firstName as firstNam3_1_1_, employee1_.lastName as lastName4_1_1_ from Address address0_ left outer join Employee employee1_ on address0_.addressId=employee1_.employeeId where address0_.addressId=?
Employee Details :
Employee [id=1, firstName=Ranga, lastName=Reddy, age=27]
Employee Address Details :
Address [addressId=1, houseNo=12345, street=SRI Nagar, city=Bangalore]
One-to-One with a shared primary key saves a column in the database and usually forces a bidirectional relationship through an ORM such as hibernate.

Happy Coding!!!

Sunday, March 1, 2015

Inheritance in Hibernate

Inheritance in Hibernate: 

Java is object oriented language and inheritance is one of main functionalities of java. Relational model can implement "is a" and "has a" relationship. Relational model supports only “has a” relationship between two entities. Hibernate can help you map such Objects with relational tables. But you need to choose certain mapping strategy based on your needs. There are three inheritance mapping strategies defined in the hibernate.


  • One table per one concrete class (TABLE_PER_CLASS)
  • One table per all hierarchical classes (SINGLE_TABLE)
  • One table per one concrete sub class (JOINED)


One table per one concrete class: This mapping is not known as good mapping for projects. In this approach every entity class has its own table i.e. table per class. All the properties of a class including inherited properties are mapped to columns of a table.

There are two ways to map the table with table per concrete class strategy.
  1. By using <union-subclass> element.
  2. By self creating the table for each class.

Lets say we have following class hierarchy.

We have Person class as base class and Employee  is subclass of Person and PermanentEmployee is Subclass of Employee.

In  table per concrete class, One table will be created for each concrete class. So there table will be three tables created( Person, Employee and PermanenetEmployee) and subclass repeats property of parent class.

Person.java
==============
package com.ranga.mapping;

import java.io.Serializable;

public class Person implements Serializable {
   private long id;
   private String firstName;
   private String lastName;
   private int age;
   // Constructors and Getter/Setter methods,
   public long getId() {
       return id;
   }
   public void setId(long id) {
       this.id = id;
   }
   public String getFirstName() {
       return firstName;
   }
   public void setFirstName(String firstName) {
       this.firstName = firstName;
   }
   public String getLastName() {
       return lastName;
   }
   public void setLastName(String lastName) {
       this.lastName = lastName;
   }
   public int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }        
}


Employee.java
====================

package com.ranga.mapping;

public class Employee extends Person {
   private String designation;
   private Double salary;
   // Constructors and Getter/Setter methods,
   public String getDesignation() {
       return designation;
   }
   public void setDesignation(String designation) {
       this.designation = designation;
   }
   public Double getSalary() {
       return salary;
   }
   public void setSalary(Double salary) {
       this.salary = salary;
   }    
}


PermanentEmployee.java
=========================
package com.ranga.mapping;


public class PermanentEmployee extends Employee {
   private double allowance;
   private int noOfLeaves;
   // Constructors and Getter/Setter methods,
   public double getAllowance() {
       return allowance;
   }
   public void setAllowance(double allowance) {
       this.allowance = allowance;
   }
   public int getNoOfLeaves() {
       return noOfLeaves;
   }
   public void setNoOfLeaves(int noOfLeaves) {
       this.noOfLeaves = noOfLeaves;
   }    
}

1. By self creating the table for each class:

Person.hbm.xml
========================
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ranga.mapping">
   <!-- Table-per-class hierarchy -->
   <class name="Person" table="Persons">
       <id name="id" />
       <property name="firstName" />
       <property name="lastName" />
       <property name="age" />        
   </class>
   <class name="Employee" table="Employees">
       <id name="id" />
       <property name="designation" />
       <property name="salary" />        
   </class>
   
   <class name="PermanentEmployee" table="PermanentEmployees">
       <id name="id" />
       <property name="allowance" />
       <property name="noOfLeaves" />        
   </class>        
</hibernate-mapping>


2. By using <union-subclass> element:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ranga.mapping">
   <!-- Table-per-class hierarchy -->
   <class name="Person" table="Persons">
       <id name="id" />
       <property name="firstName" />
       <property name="lastName" />
       <property name="age" />
       <union-subclass name="Employee" table="Employees">
           <property name="designation" />
           <property name="salary" />
       </union-subclass>      
       <union-subclass name="PermanentEmployee" table="PermanentEmployees">
           <property name="allowance" />
           <property name="noOfLeaves" />
       </union-subclass>        
   </class>    
</hibernate-mapping>

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>
       <!-- Database connection settings -->
       <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
       <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
       <property name="connection.username">ranga</property>
       <property name="connection.password">ranga</property>

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

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

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

       <!-- Drop and re-create the database schema on startup -->
       <property name="hbm2ddl.auto">create</property>


       <mapping resource="com/ranga/mapping/Person.hbm.xml" />
   </session-factory>
</hibernate-configuration>

HibernateUtil.java
=======================
package com.ranga.util;


import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
   private static final SessionFactory sessionFactory;
   private static final ServiceRegistry serviceRegistry;
   static {
       try {
           Configuration configuration = new Configuration();
           configuration.configure();
           serviceRegistry = new ServiceRegistryBuilder().applySettings(
                   configuration.getProperties()).buildServiceRegistry();
           sessionFactory = configuration.buildSessionFactory(serviceRegistry);
       } catch (Throwable ex) {
           throw new ExceptionInInitializerError(ex);
       }
   }

   public static SessionFactory getSessionFactory() {
       return sessionFactory;
   }
   
   public static void closeSessionFactory() {
       if (sessionFactory != null)
           sessionFactory.close();        
    }
}


App.java
======================
package com.ranga;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.ranga.mapping.Employee;
import com.ranga.mapping.PermanentEmployee;
import com.ranga.mapping.Person;
import com.ranga.util.HibernateUtil;

public class App
{
    public static void main( String[] args )
    {
       SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
       Session session = sessionFactory.openSession();
       session.beginTransaction();
       
       Person p1= new Person();
       p1.setId(1);
       p1.setFirstName("ranga");
       p1.setLastName("reddy");
       p1.setAge(25);
       
       Employee e1= new Employee();
       e1.setId(2);
       e1.setFirstName("raja");
       e1.setLastName("reddy");
       e1.setAge(45);
       e1.setDesignation("Project Lead");
       e1.setSalary(120000.0);
       
       PermanentEmployee pe1= new PermanentEmployee();
       pe1.setId(3);
       pe1.setFirstName("vasundra");
       pe1.setLastName("reddy");
       pe1.setAge(40);
       pe1.setDesignation("Architect");
       pe1.setSalary(150000.0);
       pe1.setNoOfLeaves(15);
       pe1.setAllowance(5000.00);
       
       session.save(p1);
       session.save(e1);
       session.save(pe1);
       
       session.getTransaction().commit();        
    }
}

[all common attributes will be duplicated]

Advantage:
  • Simple and efficient
  • Possible to define NOT NULL constraints on the table.

Disadvantage:
  • if you have a query against the super class, you will have to query several times for each sub-class tables.
  • Change in super class properties will have to be reflected in changes in each sub-class tables.
  • Data thats belongs to a parent class is scattered across a number of subclass tables, which represents concrete classes.
  • This hierarchy is not recommended for most cases.

Note: In this case there no need for the discriminator column because all entity has own table.