Need help?

Our experts will login to your server within 30 minutes to fix urgent issues.

Customer support or server support, make your own solution using our support configuration wizard.

Spring Hibernate Integration

About

In my last article, I explained about Spring and its features. Here I will explain more on how to Integrate Hibernate to Spring.What makes Spring stand out is the ease with which it can be integrated with the existing frameworks.


Hibernate, an open source application, is a powerful persistence technology for any kind of Application. Your Hibernate application can be very much simplified with the use of Spring Technology.

Steps Needed for Integrating Spring Framework with Hibernate Framework

1.) Create a Spring Project from eclipse

2.) Add the basic Jars needed for spring

#spring-2.0.6.jar
This is the main dependency JAR file. The spring framework distribution contains this file in the dist directory.

#commons-logging.jar
Spring framework internally used commons-logging API and hence we will need this file as a dependency for the spring JAR file. This file is available in the lib/jakarta-commons directory of the spring distribution.

#log4j-1.2.14.jar
For the log writer.

Remaining jars spring and hibernate integration

# asm-1.5.3.jar
#cglib-2.1_3.jar
#commons-collections-3.2.jar
#commons-logging-1.1.jar
#dom4j-1.6.1.jar
#hibernate-3.2.5.ga.jar
#jta-spec1_0_1.jar
#log4j-1.2.13.jar
#mysql-connector-java-5.0.5.jar

//Jars are available at http://www.java2s.com/Code/Jar/cocoon-2.1.10/Catalogcocoon-2.1.10.htm

3.) Create the Bean Model and database table and a mapping hbm file.

4.) Create the dao for manipulating the Models.

5.) Create the manager class for managing the dao’s.

6.) Create the mappings for the manager and dao’s in the applicationContext.xml.

7.) Instantiate the manager in the main.

Back to Top

Creating the Bean Model, Database table and mapping to a hbm file

Create table in
CREATE TABLE student (id int(12) unsigned NOT NULL auto_increment,name varchar(40) default NULL,
PRIMARY KEY (`id`))
Create a Model for the student table
public class Student {
private Long id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

Create a hbm mapping file for the Student bean and student table

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>
<hibernate-mapping>
<class name=”com.company.demo.model.Student” table=”student”>
<id name=”id” type=”java.lang.Long”>
<column name=”id” />
<generator class=”native” />
</id>
<property name=”name” type=”string”>
<column name=”name” length=”40″/>
</property>
</class>
</hibernate-mapping>

Here the name attribute in class tag indicates the class referred by the student table. ‘Id’ tag indicates the primary key and the mapping of the model field. ‘property’ tag indicates the mappings of column names and the model field names.

Back to Top

Writing the applicationContext

The applicationContext.xml file contains all the information for Spring’s Bean Factory to instantiate the necessary class es and wire the dependencies.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
default-lazy-init="true">
<!-- Datasource for database connection -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/springDB" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
<!--Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>Student.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">false</prop>
</props> </property>
</bean>
<!-- StudentDao injection of session factory-->
<bean id="studentDao"
class="com.company.demo.dao.StudentDaoHibernate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- StudentManager injection of studentDao factory-->
<bean id="studentManager" class="com.company.demo.manager.StudentManagerImpl">
<property name="studentDao" ref="studentDao" />
</bean></beans>
Back to Top

Dao and Hibernate

Wrapping interface for StudentDaoHibernate

package com.company.demo.dao;

import com.company.demo.model.Student;

public interface StudentDao {
/**
* saving the student model
* @param studentObject
*/
public void saveStudent(Student studentObject);
/**
* Get the student data by name
* @param name
* @return Student model
*/
public Student getStudent(String name);
/**
* Deleting the student
* @param object
*/
public void delete(Student object);
}

—————————-
Implementation of the Hibernate Query Language(HQL) for the Student Model

package com.company.demo.dao;

import java.util.List;

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

import com.company.demo.model.Student;

public class StudentDaoHibernate implements StudentDao {

private SessionFactory sessionFactory;
// Setter injection from application Context xml
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

public void saveStudent(Student studentObject) {
try {
Session session = sessionFactory.openSession();
session.saveOrUpdate(studentObject);
session.flush();
} catch (Exception e) {
e.printStackTrace();
}
}

public Student getStudent(String name) {
String queryStr = “from Student stu” + ” where stu.name = ? “;

Session session = sessionFactory.openSession();
Query query = session.createQuery(queryStr).setString(0, name);
List entities = query.list();
if (entities.size() > 0)
return entities.get(0);
else
return null;
}

public void delete(Student object) {
try {
Session session = sessionFactory.openSession();
session.delete(object);
session.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Back to Top

Writing the Manager

This is the Student manager Impl class for managing the dao&apss

package com.company.demo.manager;

import com.company.demo.dao.StudentDao;
import com.company.demo.model.Student;

public class StudentManagerImpl {
StudentDao studentDao;

public void saveStudent(Student s) {
studentDao.saveStudent(s);
}
public Student getStudentByName(String name){
return studentDao.getStudent(name);
}
public void deleteStudent(String name) {
studentDao.delete(this.getStudentByName(name));
}
// Setter Method for injecting the StudentDao in applicationContext.xml
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
}
Back to Top

Execution of Main

By using the Spring’s ClassPathXmlApplicationContext we can load the applicationContext.xml in the classpath. The spring framework will locate it automatically through the class path searching mechanism.
By using the getBean method, the Beans constructors are instantiated and the setter injections are loaded from applicationContext references.
——-

package com.company.demo.main;

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

import com.company.demo.manager.StudentManagerImpl;
import com.company.demo.model.Student;

public class Main {

public Main() {
// Loading the applicationContext xml.
ApplicationContext ctx = new ClassPathXmlApplicationContext(
“applicationContext.xml”);
// Instantiating the manager bean
StudentManagerImpl manager = (StudentManagerImpl) ctx.getBean(”studentManager”);
Student stud = new Student();
stud.setName(”Girish”);
// Saving the Student Model
manager.saveStudent(stud);

Student savedStud = manager.getStudentByName(stud.getName());
System.out.println(savedStud.getId() + ” ::: ” + savedStud.getName());
manager.deleteStudent(stud.getName());
Student savedStud1 = manager.getStudentByName(stud.getName());
System.out.println(savedStud1);
}
public static void main(String[] args) {
new Main();
}
}

Run the Main class, for inserting the Student row and deleting that row.

Back to Top

Conclusion:

Spring is new in the market and provides a fresh approach to framework development. Spring tries to integrate with the existing solutions like Hibernate, JDO and AOP rather than duplicate them. As of now, Spring can easily be integrated and used in an eclipse IDE.

Back to Top

References

Tutorial :
http://static.springframework.org/spring/docs/2.5.x/reference/beans.html

Hibernate Forum

http://forum.hibernate.org

Hibernate Home page:

http://hibernate.org

Eclipse Home Page:

http://www.eclipse.org

Installation and sample projects:
1.) http://www.java2s.com/Code/Java/Hibernate/SpringDaoInjection.htm
2.)http://www.java2s.com/Code/Java/Hibernate/SpringHibernateTemplateSaveOrUpdate.htm

Back to Top

About the author:

Girish Kodupurath, a Senior Software Engineer at Bobcares, working since January 2007. He is a SCJP certified Java developer and also has experience in developing web based PHP applications. His major achievement lies in the contribution to the open source project VTONF. He is passionate in writing parsing scripts and JAVA programs.



Java

5 Comments

  1. Hi,

    This article is of great help. I am new to Spring and Hibernate.
    I am curious to know how to use JUnit along with spring, hibernate.
    Any help will be appreciated!

    Regards
    Gireesh

  2. What will be the Story when i want to integrate spring+hibernate with annotations ?

  3. Hi Gireesh,

    Spring provides support for Junit Tests. You can write your junit tests by extending the Test class with “org.springframework.test.AbstractTransactionalDataSourceSpringContextTests”. Rollback is true by default.

    Thanks & Regards,
    Girish.K

  4. Hi Nirav,

    The story will be same except our .hbm files will replaced with annotations in the Models.

    In example i mentioned, the changes will be as follows:

    @Entity
    @Table(name=”student”)
    public class Student {
    private Long id;
    private String name;

    @Column(name=”name”, nullable=true, length=40, unique=false)
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }

    @Id @GeneratedValue(strategy=AUTO) @Column(name=”id”)
    public Long getId() {
    return id;
    }
    public void setId(Long id) {
    this.id = id;
    }
    }

    Thanks & Regards,
    Girish.K

  5. hi …this u r writen in good manner and it is helpful also.

Bobcares
Bobcares is a server management company that helps businesses deliver uninterrupted and secure online services. Our engineers manage close to 51,500 servers that include virtualized servers, cloud infrastructure, physical server clusters, and more.
MORE ABOUT BOBCARES