Spring JDBC : Integration with Hibernate

It is common to see enterprise Java application using  Spring and Hibernate integration. We will be building on our exsisting  spring jdbc application. I am using MYSQL DB which has a ’employee’ table with test data.
We need to add spring-orm and hibernate denpendecies in pom.xml:

<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">
 <!-- Core utilities used by other modules. Define this if you use Spring
 Utility APIs (org.springframework.core.*/org.springframework.util.*) -->

<!-- Bean Factory and JavaBeans utilities (depends on spring-core) Define
 this if you use Spring Bean APIs (org.springframework.beans.*) -->

<!-- Application Context (depends on spring-core, spring-expression, spring-aop,
 spring-beans) This is the central artifact for Spring's Dependency Injection
 Container and is generally always defined -->


Notice the last 2 dependencies. All the related depencies will be automatically be downloaded by maven.
Our Entity class Employee.java

package mynotes.spring.hibernateModel;

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

public class Employee{
 private int id;
 private String name;
 private String phone;

 public String toString() {
 return ("Id=>" + this.id + " Name=>" + this.name+ " phone=>"
 + this.phone);

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 String getPhone() {
 return phone;

public void setPhone(String phone) {
 this.phone = phone;


Writing our Dao class MySpringHibernateDao

package mynotes.spring.hibernateMain;

import mynotes.spring.hibernateModel.Employee;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

public class MySpringHibernateDao {

 private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
 return sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory) {
 this.sessionFactory = sessionFactory;

public Employee getEmployeeByid(int id) {
 return (Employee) getSessionFactory().openSession().get(Employee.class,id);



As you know hibernate needs a SessionFactory object to create sessions and we use this session to run our queries. Usually one application will only have one SessionFactory. We have a private sessionFactory memeber varaible which is autowired. we will create this bean in spring.xml. The getemployeeByid is the method which takes in an int and return the corresponding Employee with that id. This is achieved by opeing the session using sessionFactory and using get() method of hibernate.
Notice the stereotype @Repository over the class. This makes it a bean. Now you can annotate @Component instead and this will work perfectly fine, but by annotating them with @Repository, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. The @Repository annotation carries with it some additional functionality, it causes exceptions to be wrapped up as DataAccessExceptions.Few stereotype annotation :

@Component – generic stereotype for any Spring-managed component

@Repository – stereotype for persistence layer

@Service – stereotype for service layer

@Controller – stereotype for presentation layer (spring-mvc)

Writing out spring.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"

<context:annotation-config />
<context:component-scan base-package="mynotes.spring.hibernateMain" />

<bean id="dataSource"
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/javatest" />
<property name="username" value="root" />
<property name="password" value="admin" />

<bean id="sessionFactory"
<property name="dataSource" ref="dataSource"></property>
<property name="packagesToScan" value="mynotes.spring.hibernateModel" />
<property name="hibernateProperties">
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>


Notice the sessionFactoryBean. Since we are using Hibernate 4 , we would be using LocalSessionFactoryBean. The bean is initialised with the datasource. Also we need to tell sessionFactory about our model classes that would use in persistance, therefore we used the property ‘packagesToScan‘. In order to initialise hibernate properties we use the property ‘hibernateProperties‘. All the hibernate properties are spanned by <props> and mentioned as key. Because we are using mysql, we would be using MySQLDialect. The show_sql property is setted as true to print the hibernate generated queries. and hbm2ddl.auto is kept as update so that the exsistig table in DB could be used (without any droping and then creating new).

Tesing using App.java:

package mynotes.spring.hibernateMain;

import mynotes.spring.hibernateModel.Employee;

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

public class App {

public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("/mynotes/spring/hibernateMain/spring.xml");
MySpringHibernateDao mySpringHibernateDao=context.getBean("mySpringHibernateDao",MySpringHibernateDao.class);
Employee employee=mySpringHibernateDao.getEmployeeByid(2);


Hibernate: select employee0_.id as id1_0_0_, employee0_.name as name2_0_0_, employee0_.phone as phone3_0_0_ from Employee employee0_ where employee0_.id=?
Id=>2 Name=>Jane phone=>234567


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: