Update using JdbcTemplate

Note: <context:annotation-config/>, <context:component-scan>, @Component and @Autowired are explained under the "Points to ponder" section of the post JbdcTemplate example
Below program is an example of how to update record into data base using JdbcTempalte.
File: com.ram.model.Departments.java
package com.ram.model;

public class Departments {
 private int department_id;
 private String department_name;
 private int manager_id;
 private int location_id;
 
 public int getDepartment_id() {
  return department_id;
 }
 public void setDepartment_id(int department_id) {
  this.department_id = department_id;
 }
 public String getDepartment_name() {
  return department_name;
 }
 public void setDepartment_name(String department_name) {
  this.department_name = department_name;
 }
 public int getManager_id() {
  return manager_id;
 }
 public void setManager_id(int manager_id) {
  this.manager_id = manager_id;
 }
 public int getLocation_id() {
  return location_id;
 }
 public void setLocation_id(int location_id) {
  this.location_id = location_id;
 }
}

Next create applicationContext.xml file under src. The file is given below.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 
 <context:annotation-config/>
 
 <context:component-scan base-package="com.ram.dao"></context:component-scan>
 
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
  <property name="url" value="dbc:oracle:thin:@localhost:1521:xe"></property>
  <property name="username" value="hr"></property>
  <property name="password" value="hr"></property>
 </bean>
 
</beans>
File: com.ram.dao.DepartmentsDaoImpl.java
package com.ram.dao;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class DepartmentsDaoImpl {
 private JdbcTemplate jdbcTemplate;
 private DataSource dataSource;
 
 public void insertDepartment(){
  String sql = "insert into departments(department_id, department_name, location_id) values (?,?,?)";
  jdbcTemplate.update(sql, new Object[]{280, "ABC", 1700});
 }
 
 public JdbcTemplate getJdbcTemplate() {
  return jdbcTemplate;
 }
 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  this.jdbcTemplate = jdbcTemplate;
 }
 public DataSource getDataSource() {
  return dataSource;
 }
 @Autowired
 public void setDataSource(DataSource dataSource) {
  this.jdbcTemplate = new JdbcTemplate(dataSource);
 }
 
}

File: com.ram.main.DepartmentApp.java
package com.ram.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ram.dao.DepartmentsDaoImpl;

public class DepartmentApp {
 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  DepartmentsDaoImpl dao = context.getBean("departmentsDaoImpl", DepartmentsDaoImpl.class);
  
  dao.insertDepartment();
 }
}

Execute DepartmentApp.java file. Output is given below.

Using RowMapper

Note: <context:annotation-config/>, <context:component-scan>, @Component and @Autowired are explained under the "Points to ponder" section of the post JbdcTemplate example
Below program is an example of how to get all the columns and all the rows from the database using RowMapper.
File: com.ram.model.Departments.java
package com.ram.model;

public class Departments {
 private int department_id;
 private String department_name;
 private int manager_id;
 private int location_id;
 
 public int getDepartment_id() {
  return department_id;
 }
 public void setDepartment_id(int department_id) {
  this.department_id = department_id;
 }
 public String getDepartment_name() {
  return department_name;
 }
 public void setDepartment_name(String department_name) {
  this.department_name = department_name;
 }
 public int getManager_id() {
  return manager_id;
 }
 public void setManager_id(int manager_id) {
  this.manager_id = manager_id;
 }
 public int getLocation_id() {
  return location_id;
 }
 public void setLocation_id(int location_id) {
  this.location_id = location_id;
 }
}

Next create applicationContext.xml file under src. The file is given below.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 
 <context:annotation-config/>
 
 <context:component-scan base-package="com.ram.dao"></context:component-scan>
 
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
  <property name="url" value="dbc:oracle:thin:@localhost:1521:xe"></property>
  <property name="username" value="hr"></property>
  <property name="password" value="hr"></property>
 </bean>
 
</beans>
File: com.ram.dao.DepartmentsDaoImpl.java
package com.ram.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import com.ram.model.Departments;

@Component
public class DepartmentsDaoImpl {
 private DataSource dataSource;
 private JdbcTemplate jdbcTemplate;

 public List<Departments> getAllDepartments(){
  String query = "select * from departments";
  return jdbcTemplate.query(query, new DepartmentMapper());
 }

 public static final class DepartmentMapper implements RowMapper{
  @Override
  public Departments mapRow(ResultSet resultSet, int rowNum) throws SQLException{
   Departments departments = new Departments();
   departments.setDepartment_id(resultSet.getInt("department_id"));
   departments.setDepartment_name(resultSet.getString("department_name"));
   departments.setManager_id(resultSet.getInt("manager_id"));
   departments.setLocation_id(resultSet.getInt("location_id"));
   return departments;
  }
 }

 public DataSource getDataSource() {
  return dataSource;
 }
 @Autowired
 public void setDataSource(DataSource dataSource) {
  this.jdbcTemplate = new JdbcTemplate(dataSource);
 }
 public JdbcTemplate getJdbcTemplate() {
  return jdbcTemplate;
 }
 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  this.jdbcTemplate = jdbcTemplate;
 }
}


File: com.ram.main.DepartmentApp.java
package com.ram.main;

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ram.dao.DepartmentsDaoImpl;
import com.ram.model.Departments;

public class DepartmentApp {
 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  DepartmentsDaoImpl dao = context.getBean("departmentsDaoImpl", DepartmentsDaoImpl.class);
  List<Departments> departments = dao.getAllDepartments();
  
  for(Departments dept : departments){
   System.out.print("Department_id = "+dept.getDepartment_id());
   System.out.print("\tDepartment_name = "+dept.getDepartment_name());
   System.out.print("\tManager_id = "+dept.getManager_id());
   System.out.println("\tLocation_id = "+dept.getLocation_id());
  }
 }
}

Execute DepartmentApp.java file. Output is given below.

Passing parameters

Note: <context:annotation-config/>, <context:component-scan>, @Component and @Autowired are explained under the "Points to ponder" section of the post JbdcTemplate example
Below program is an example of how to get the data from the database using JdbcTemplateby passing a parameter.
File: com.ram.model.Departments.java
package com.ram.model;

public class Departments {
 private int department_id;
 private String department_name;
 private int manager_id;
 private int location_id;
 
 public int getDepartment_id() {
  return department_id;
 }
 public void setDepartment_id(int department_id) {
  this.department_id = department_id;
 }
 public String getDepartment_name() {
  return department_name;
 }
 public void setDepartment_name(String department_name) {
  this.department_name = department_name;
 }
 public int getManager_id() {
  return manager_id;
 }
 public void setManager_id(int manager_id) {
  this.manager_id = manager_id;
 }
 public int getLocation_id() {
  return location_id;
 }
 public void setLocation_id(int location_id) {
  this.location_id = location_id;
 }
}

Next create applicationContext.xml file under src. The file is given below.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 
 <context:annotation-config/>
 
 <context:component-scan base-package="com.ram.dao"></context:component-scan>
 
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
  <property name="url" value="dbc:oracle:thin:@localhost:1521:xe"></property>
  <property name="username" value="hr"></property>
  <property name="password" value="hr"></property>
 </bean>
 
</beans>
File: com.ram.dao.DepartmentsDaoImpl.java
package com.ram.dao;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class DepartmentsDaoImpl {
 private DataSource dataSource;
 private JdbcTemplate jdbcTemplate;
 
 //Method to get the Department_name given department_id
 public String getDepartmentName(int department_id){
  String sql = "select department_name from departments where department_id = ?";
  return jdbcTemplate.queryForObject(sql, new Object[] {department_id}, String.class);
 }
 
 public DataSource getDataSource() {
  return dataSource;
 }
 
 @Autowired
 public void setDataSource(DataSource dataSource) {
  this.jdbcTemplate = new JdbcTemplate(dataSource);
 }
 public JdbcTemplate getJdbcTemplate() {
  return jdbcTemplate;
 }
 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  this.jdbcTemplate = jdbcTemplate;
 }
 
}

File: com.ram.main.DepartmentApp.java
package com.ram.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ram.dao.DepartmentsDaoImpl;

public class DepartmentApp {
 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  DepartmentsDaoImpl departments = context.getBean("departmentsDaoImpl", DepartmentsDaoImpl.class);
  System.out.println("Depatment name for department_id 30 is "+departments.getDepartmentName(30));
 }
}


Execute DepartmentApp.java file. Output is given below.

JbdcTemplate example

Points to ponder:
  • <context:annotation-config/> : It is used to activate annotations in beans already registered in the application context.
  • <context:component-scan/> : It scans packages to find and register beans within the application context.
  • @Component : It is one of several stereotype annotations. @Component is a general-purpose stereotype annotation indicating that the class is a Spring component
  • @Autowired : @Autowired indicates that spring should inject dependency, based on its type or based on its name if used with the @Qualifier annotation.
Below program is an example of how to connect to data base using JdbcTemplate.
File: com.ram.model.Departments.java
package com.ram.model;

public class Departments {
 private int department_id;
 private String department_name;
 private int manager_id;
 private int location_id;
 
 public int getDepartment_id() {
  return department_id;
 }
 public void setDepartment_id(int department_id) {
  this.department_id = department_id;
 }
 public String getDepartment_name() {
  return department_name;
 }
 public void setDepartment_name(String department_name) {
  this.department_name = department_name;
 }
 public int getManager_id() {
  return manager_id;
 }
 public void setManager_id(int manager_id) {
  this.manager_id = manager_id;
 }
 public int getLocation_id() {
  return location_id;
 }
 public void setLocation_id(int location_id) {
  this.location_id = location_id;
 }
}

Next create applicationContext.xml file under src. The file is given below.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
 
 <context:annotation-config/>
 
 <context:component-scan base-package="com.ram.dao"></context:component-scan>
 
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
  <property name="url" value="dbc:oracle:thin:@localhost:1521:xe"></property>
  <property name="username" value="hr"></property>
  <property name="password" value="hr"></property>
 </bean>
 
</beans>
File: com.ram.dao.DepartmentsDaoImpl.java
package com.ram.dao;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class DepartmentsDaoImpl {
 private DataSource dataSource;
 private JdbcTemplate jdbcTemplate;
 
 //Method to get the number of rows in departments table
 public int getDepartmentsCount(){
  String sql = "select count(*) from departments";
  return jdbcTemplate.queryForInt(sql);
 }
 
 public DataSource getDataSource() {
  return dataSource;
 }
 
 @Autowired
 public void setDataSource(DataSource dataSource) {
  this.jdbcTemplate = new JdbcTemplate(dataSource);
 }
 public JdbcTemplate getJdbcTemplate() {
  return jdbcTemplate;
 }
 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  this.jdbcTemplate = jdbcTemplate;
 }
 
}

File: com.ram.main.DepartmentsDao.java
package com.ram.main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ram.dao.DepartmentsDaoImpl;

public class DepartmentsDao {
 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  DepartmentsDaoImpl departments = context.getBean("departmentsDaoImpl", DepartmentsDaoImpl.class);
  System.out.println("Total number of rows in Departments table = "+departments.getDepartmentsCount());
 }
}

Execute DepartmentsDao.java file. Output is given below.

Criteria API example

Criteria API is yet another way of retrieving values from database provided by hibernate. Using HQL has some disadvantages. If we write complex queries using HQL, at some point of time these queries look much similar to our traditional sql queries. To overcome with this issue, hibernate has provided us with the criteria api. Criteria is a simplified API for retrieving by composing criterion objects. This is very convenient approach for functionality like "search" screens where there is a variable number for conditions to be placed upon the result search.Below is a simple example of how to use a criteria API.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Jobs"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Jobs.java
package com.ram.dao;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Jobs {
 @Id
 private String job_id;
 private String job_title;
 private int min_salary;
 private int max_salary;
 
 public String getJob_id() {
  return job_id;
 }
 public void setJob_id(String job_id) {
  this.job_id = job_id;
 }
 public String getJob_title() {
  return job_title;
 }
 public void setJob_title(String job_title) {
  this.job_title = job_title;
 }
 public int getMin_salary() {
  return min_salary;
 }
 public void setMin_salary(int min_salary) {
  this.min_salary = min_salary;
 }
 public int getMax_salary() {
  return max_salary;
 }
 public void setMax_salary(int max_salary) {
  this.max_salary = max_salary;
 }
}

File: com.ram.hibernate.CriteriaAPIExample.java
package com.ram.hibernate;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;

import com.ram.dao.Jobs;

public class CriteriaAPIExample {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  
  Criteria criteria = session.createCriteria(Jobs.class);
  criteria.add(Restrictions.eq("job_id", "MK_MAN"));
  
  List jobs = (List) criteria.list();
  
  for(Jobs job: jobs){
   System.out.println("Jon Id: "+job.getJob_id());
   System.out.println("Job Title "+job.getJob_title());
   System.out.println("Minimum Salary "+job.getMin_salary());
   System.out.println("Maximum Salary "+job.getMax_salary());
  }
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute CriteriaAPIExample.java and you get the output as shown below.

Native query example

Instead of using HQL or Hibernate Query Language, hibernate provides us with an annotation where we can use native sql queries i.e., queries that we usually write in our data bases. To achieve this we can make use of "@NamedNativeQuery" annotation. This annotation takes in three parameters. First one being the name of the query with which it should be called in the main program. Second parameter is the native query itself. Third parameter is the name of the class where it needs to store the list of values when the query gets executed. We have not mentioned this parameter in our previous post for the "@NamedQuery" because, for @NamedQuery we have used class name in the query instead of table name. So in this case hibernate knows in which class it needs to store the results. Below is a sample program for the native queries.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Student"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Student.java
package com.ram.dao;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedNativeQuery;

@Entity
@NamedNativeQuery(name="Student.byName", query="select * from Student where studentname = ?", resultClass=Student.class)
public class Student {
 @Id @GeneratedValue
 private int studentId;
 private String studentName;
 
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
}

File: com.ram.hibernate.HQLParameterExample.java
package com.ram.hibernate;

import java.util.List;

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

import com.ram.dao.Student;

public class NamedNativeQueryExample {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  
  Query query = session.getNamedQuery("Student.byName");
  query.setString(0, "Student 3");
  List students = (List) query.list();
  
  for(Student stud: students){
   System.out.println("Student Name: "+stud.getStudentName());
  }
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute NamedNativeQueryExample.java and you get the output as shown below.

Named Query example

Instead of writing queries in the main program wherer they are executed, hibernate provides us with a way where we can write queries in the entity class using the annotation "@NamedQuery". The @NamedQuery annotation takes 2 parameters. One is the name of the query using which it should be called and the next is the query. Below is a sample program which explains how to use a named query.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Student"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Student.java
package com.ram.dao;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;

@Entity
@NamedQuery(name="Student.Id",query="from Student where studentId > ?")
public class Student {
 @Id @GeneratedValue
 private int studentId;
 private String studentName;
 
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
}

File: com.ram.hibernate.HQLParameterExample.java
package com.ram.hibernate;

import java.util.List;

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

import com.ram.dao.Student;

public class NamedQueryExample {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  
  Query query = session.getNamedQuery("Student.Id");
  query.setInteger(0, 3);
  List<Student> students = (List<Student>) query.list();
  
  for(Student stud: students){
   System.out.print("Student Id : "+stud.getStudentId());
   System.out.println("Student Name: "+stud.getStudentName());
  }
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute NamedQueryExample.java and you get the output as shown below.

HQL setParameter example

The below example shows how to use setParameter in HQL queries.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Student"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Student.java
package com.ram.dao;

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

@Entity
public class Student {
 @Id @GeneratedValue
 private int studentId;
 private String studentName;
 
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
}

File: com.ram.hibernate.HQLParameterExample.java
package com.ram.hibernate;

import java.util.List;

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

import com.ram.dao.Student;

public class HQLParameterExample {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  
  Query query = session.createQuery("from Student where studentId > :id1 and studentId < :id2");
  query.setParameter("id1", 2);
  query.setParameter("id2", 8);
  List<Student> students = (List<Student>) query.list();
  
  for(Student stud: students){
   System.out.print("Student Id : "+stud.getStudentId());
   System.out.println("Student Name: "+stud.getStudentName());
  }
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute HQLParameterExample.java and you get the output as shown below.

HQL Select clause example

The below example shows how to use select clause for the HQL and then retrieve values.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Student"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Student.java
package com.ram.dao;

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

@Entity
public class Student {
 @Id @GeneratedValue
 private int studentId;
 private String studentName;
 
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
}

File: com.ram.hibernate.HQLSelectExample.java
package com.ram.hibernate;

import java.util.Iterator;
import java.util.List;

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

import com.ram.dao.Student;

public class HQLSelectExample {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  
  Query query = session.createQuery("select studentId, studentName from Student");
  query.setFirstResult(3);
  query.setMaxResults(5);
  
  List<Student> students = query.list();
  Iterator it = students.iterator();
  
  while(it.hasNext()){
   Object[] obj = (Object[]) it.next();
   int id = (Integer) obj[0];
   String name = (String) obj[1];
   System.out.print("Student Id = "+id);
   System.out.println("\t Student Name = "+name);
  }
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute HQLSelectExample.java and you get the output as shown below.

Pagination example

While developing application, there comes a situation where we do not want to retrieve all the values at once. As per the user requirement we have to fetch may be first 10 rows at a time and the next rows for the next request and so on. This feature is called pagination and HQL helps us in achieving this feature.
After querying for all the records required, we have to set two properties in the query. They are setFirstResult and setMaxResults. In the below example we have setFirstResult to 3, which means that we are asking hibernate to skip the first 3 records in the table. And then we set the setMaxResults to 5. This means that after skipping the first 3 results, hibernate has to pull the next 5 recods in the database. The result of this is printed in the console.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Student"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Student.java
package com.ram.dao;

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

@Entity
public class Student {
 @Id @GeneratedValue
 private int studentId;
 private String studentName;
 
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
}

File: com.ram.hibernate.Pagination.java
package com.ram.hibernate;

import java.util.List;

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

import com.ram.dao.Student;

public class Pagination {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  
  Query query = session.createQuery("from Student");
  query.setFirstResult(3);
  query.setMaxResults(5);
  
  List students = (List) query.list();
  for(Student stud: students){
   System.out.print("Student Id = "+stud.getStudentId());
   System.out.println("\tStudent Name = "+stud.getStudentName());
  }
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute Pagination.java and you get the output as shown below.

HQL example

The below program uses HQL which stands for Hibernate Query Language. In HQL we use class names instead of table names. And instead of using column names for the where clause, we use member variables. Also, note that if we want to retrieve all the records from the table, there is no need to use "select" clause. Below program retrieves student id's in between 2 and 8 and displays them in the console.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Student"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Student.java
package com.ram.dao;

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

@Entity
public class Student {
 @Id @GeneratedValue
 private int studentId;
 private String studentName;
 
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
}

File: com.ram.hibernate.HQLExample.java
package com.ram.hibernate;

import java.util.Iterator;
import java.util.List;

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

import com.ram.dao.Student;

public class HQLExample {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  session.beginTransaction();
  
  Query query = session.createQuery("from Student where studentId > 2 and studentId < 8");
  List students = query.list();
  System.out.println("No.of students between 2 and 8 are "+students.size());
  
  for(Iterator it = students.iterator(); it.hasNext();){
   Student stud = it.next();
   System.out.print("Student Id = "+stud.getStudentId());
   System.out.println("\tStudent Name = "+stud.getStudentName());
  }
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute HQLExample.java and you get the output as shown below.

Delete example

The below program is to delete a student from the database.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Student"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Student.java
package com.ram.dao;

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

@Entity
public class Student {
 @Id @GeneratedValue
 private int studentId;
 private String studentName;
 
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
}

The below program is to delete a student from the database. File: com.ram.hibernate.CRUDExample.java
package com.ram.hibernate;

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

import com.ram.dao.Student;

public class CRUDExample {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  
  session.beginTransaction();
  
  //Delete
  Student student = (Student) session.get(Student.class, 5);
  System.out.println(student.getStudentName());
  session.delete(student);
  
  session.getTransaction().commit();
  session.close();
 }
}

Update example

The below program is to update a student name in the database.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Student"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Student.java
package com.ram.dao;

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

@Entity
public class Student {
 @Id @GeneratedValue
 private int studentId;
 private String studentName;
 
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
}

File: com.ram.hibernate.CRUDExample.java
package com.ram.hibernate;

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

import com.ram.dao.Student;

public class CRUDExample {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  
  session.beginTransaction();
  
  //Update
  Student student = (Student) session.get(Student.class, 5);
  student.setStudentName("Student 5 updated");
  session.update(student);
  
  session.getTransaction().commit();
  session.close();
 }
}

Retrieve example

Below is an example for Retrieve operation in hibernate.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Student"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Student.java
package com.ram.dao;

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

@Entity
public class Student {
 @Id @GeneratedValue
 private int studentId;
 private String studentName;
 
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
}

File: com.ram.hibernate.CRUDExample.java
package com.ram.hibernate;

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

import com.ram.dao.Student;

public class CRUDExample {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  
  session.beginTransaction();
  
  //Retrieve
  Student student = (Student) session.get(Student.class, 5);
  System.out.println("Retrieved student name is "+student.getStudentName());
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute CRUDExample.java and you get the below output.

CRUD operations

Below is an example for Create operation in hibernate.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Student"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Student.java
package com.ram.dao;

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

@Entity
public class Student {
 @Id @GeneratedValue
 private int studentId;
 private String studentName;
 
 public int getStudentId() {
  return studentId;
 }
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
}

File: com.ram.hibernate.CRUDExample.java
package com.ram.hibernate;

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

import com.ram.dao.Student;

public class CRUDExample {
 public static void main(String[] args) {
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  
  session.beginTransaction();
  
  //Create
  for(int i=1; i<=10; i++){
   Student student = new Student();
   student.setStudentName("Student "+i);
   session.save(student);
  }
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute the CRUDExample.java and you get the below output.

Joined Inheritance

Hibernate provides with another strategy of inheritance which is "Joined". This strategy is similar to table per class because even in this strategy hibernate creates separate tables for the entities. Internally hibernate uses the Join table concepts of the database.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Vehicle"/>
        <mapping class="com.ram.dao.TwoWheeler"/>
        <mapping class="com.ram.dao.FourWheeler"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Vehicle.java
package com.ram.dao;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Vehicle {
 @Id @GeneratedValue
 private int vehicleId;
 private String vehicleName;
 
 public int getVehicleId() {
  return vehicleId;
 }
 public void setVehicleId(int vehicleId) {
  this.vehicleId = vehicleId;
 }
 public String getVehicleName() {
  return vehicleName;
 }
 public void setVehicleName(String vehicleName) {
  this.vehicleName = vehicleName;
 }
}

File: com.ram.dao.TwoWheeler.java
package com.ram.dao;

import javax.persistence.Entity;

@Entity
public class TwoWheeler extends Vehicle {
 private String steeringHandle;

 public String getSteeringHandle() {
  return steeringHandle;
 }

 public void setSteeringHandle(String steeringHandle) {
  this.steeringHandle = steeringHandle;
 }
}

File: com.ram.dao.FourWheeler.java
package com.ram.dao;

import javax.persistence.Entity;

@Entity
public class FourWheeler extends Vehicle {
 private String steeringWheel;

 public String getSteeringWheel() {
  return steeringWheel;
 }

 public void setSteeringWheel(String steeringWheel) {
  this.steeringWheel = steeringWheel;
 }
}

File: com.ram.hibernate.JoinedInheritanceExample.java
package com.ram.hibernate;

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

import com.ram.dao.FourWheeler;
import com.ram.dao.TwoWheeler;
import com.ram.dao.Vehicle;

public class JoinedInheritanceExample {
 public static void main(String[] args) {
  Vehicle vehicle = new Vehicle();
  vehicle.setVehicleName("Car");
  
  TwoWheeler yamaha = new TwoWheeler();
  yamaha.setVehicleName("Yamaha");
  yamaha.setSteeringHandle("Yamaha steering handle");
  
  FourWheeler benz = new FourWheeler();
  benz.setVehicleName("Benz");
  benz.setSteeringWheel("Benz steering wheel");
  
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  
  session.beginTransaction();
  session.save(vehicle);
  session.save(yamaha);
  session.save(benz);
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute the JoinedInheritanceExample.java and you get the below output.

Table Per Class Inheritance

In this post we will see the next strategy that hibernate uses while creating tables. In the strategy attribute of the @Inheritance annotation, if we use "TABLE_PER_CLASS", then hibernate creates a separate table for each entity. The below program explains how to achieve this.
<?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 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">hr</property>
        <property name="connection.password">hr</property>

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

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</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>

        <!-- Names the annotated entity class -->
        <mapping class="com.ram.dao.Vehicle"/>
        <mapping class="com.ram.dao.TwoWheeler"/>
        <mapping class="com.ram.dao.FourWheeler"/>

    </session-factory>

</hibernate-configuration>
File: com.ram.dao.Vehicle.java
package com.ram.dao;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Vehicle {
 @Id @GeneratedValue
 private int vehicleId;
 private String vehicleName;
 
 public int getVehicleId() {
  return vehicleId;
 }
 public void setVehicleId(int vehicleId) {
  this.vehicleId = vehicleId;
 }
 public String getVehicleName() {
  return vehicleName;
 }
 public void setVehicleName(String vehicleName) {
  this.vehicleName = vehicleName;
 }
}

File: com.ram.dao.TwoWheeler.java
package com.ram.dao;

import javax.persistence.Entity;

@Entity
public class TwoWheeler extends Vehicle {
 private String steeringHandle;

 public String getSteeringHandle() {
  return steeringHandle;
 }

 public void setSteeringHandle(String steeringHandle) {
  this.steeringHandle = steeringHandle;
 }
}

File: com.ram.dao.FourWheeler.java
package com.ram.dao;

import javax.persistence.Entity;

@Entity
public class FourWheeler extends Vehicle {
 private String steeringWheel;

 public String getSteeringWheel() {
  return steeringWheel;
 }

 public void setSteeringWheel(String steeringWheel) {
  this.steeringWheel = steeringWheel;
 }
}

File: com.ram.hibernate.TablePerClassExample.java
package com.ram.hibernate;

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

import com.ram.dao.FourWheeler;
import com.ram.dao.TwoWheeler;
import com.ram.dao.Vehicle;

public class TablePerClassExample {
 public static void main(String[] args) {
  Vehicle vehicle = new Vehicle();
  vehicle.setVehicleName("Car");
  
  TwoWheeler yamaha = new TwoWheeler();
  yamaha.setVehicleName("Yamaha");
  yamaha.setSteeringHandle("Yamaha steering handle");
  
  FourWheeler benz = new FourWheeler();
  benz.setVehicleName("Benz");
  benz.setSteeringWheel("Benz steering wheel");
  
  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  
  session.beginTransaction();
  session.save(vehicle);
  session.save(yamaha);
  session.save(benz);
  
  session.getTransaction().commit();
  session.close();
 }
}

Execute the TablePerClassExample.java and you get the below output.