Thursday, May 28, 2009

Spring + Hibernate


Spring + Hibernate


This article is for those who know spring and hibernate but never integrated or run them together. I hope you know both of these technologies as I am not going in detail of these :)

Steps to integrate hibernate and spring are as follows:
1. Jars for hibernate, spring and the dependencies (Use maven for this, I will be adding pom.xml file for your reference).
2. Mapping and Configuration files of hibernate.
3. And off-course you have to have the spring bean xml file.

I will split this tutorial into three parts:
1. Develop Hibernate Application
2. Using hibernate with Spring Framework.
3. Running the Example Application.


Developing Hibernate Application:
We will have employee as entity with which we are going play with.

First will look into how we do this in traditional way means with standalone client:
1. Will have Employee POJO class
Employee.java
---------------------------------------------
package com.ideeksha;

public class Employee {

private Long employeeCode;
private String employeeName;
private int employeesalary;

public Long getEmployeeCode() {
return employeeCode;
}
public void setEmployeeCode(Long employeeCode) {
this.employeeCode = employeeCode;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public int getEmployeesalary() {
return employeesalary;
}
public void setEmployeesalary(int employeesalary) {
this.employeesalary = employeesalary;
}
}

2. Then will have the mapping file

Employee.hbm.xml
---------------------------------------------

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ideeksha">
<class name="Employee" table="EMP">
<id name="employeeCode" column="EMP_CODE" type="long">
<generator class="increment"></generator>
</id>
<property name="employeeName" column="NAME" type="string"></property>
<property name="employeesalary"></property>
</class>
</hibernate-mapping>

3. And the configuration file :

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>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">tiger</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:machinename</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</property>

<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>

<mapping resource="Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>
4. Offcourse the main class to run this :

PersistEmployee.java
--------------------------------------------------------


package com.ideeksha;

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

public class PersistEmp {

/**
* @param args
*/
public static void main(String[] args) {
SessionFactory factory=null;
Session session = null;
Transaction tx = null;

try
{
factory = new Configuration().configure().buildSessionFactory();
session = factory.openSession();
tx = session.beginTransaction();

Employee emp = new Employee();
emp.setEmployeeName("Anil Verma");

session.save(emp);


tx.commit();

}catch (Exception e) {
tx.rollback();
e.printStackTrace();
}finally
{
session.close();
factory.close();
}


}

}


Yes!! you have developed your simple hibernate application.

2. Using hibernate with Spring Framework.

And now time is come to integrate this to Spring.Configuring the Hibernate SessionFactory in Spring.Here is an example Hibernate SessionFactory configured in Spring. You will be using this instead of the typical hibernate-config.xml. All we are doing here is telling Hibernate/Spring what our Hibernate mapping files are:

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>

<value>Employee.hbm.xml</value>
</list>
</property>
</bean>

If you have a hibernate.properties in your classpath, the Spring LocalSessionFactoryBean will use that file to configure the database connections, dialect and pooling. Alternatively, you can define a DataSource in Spring (any class that implements javax.sql.DataSource) and explicity set all of your Hibernate properties in the LocalSessionFactoryBean:

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>

</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle9iDialect
</prop>
</props>

</property>
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName">
<value> oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value> jdbc:oracle:thin:@localhost:1521:machinename</value>

</property>
<property name="username"><value>scott</value></property>
<property name="password"><value>tiger</value></property>
</bean>


Extending HibernateDaoSupport for the Actual DAO Implementation
The Spring HibernateDaoSupport class provides all kinds of convenience methods for working with Hibernate. Most of these are accessible via the HibernateTemplate object that this class exposes.
Anyway, here is our EmployeeDAO implemented by extending HibernateDaoSupport:

EmployeeDAOImpl.java
-----------------------------------------
package com.ideeksha;
public class EmployeeDAOImpl
extends HibernateDaoSupport
implements EmployeeDAO
{
/**
* Returns a java.util.List of all Employees in the system.
* @return
*/
public Collection getEmployees()
{
return getHibernateTemplate().loadAll(Employee.class);
}

/**
* Get a Employee Object given the id
* @param id
* @return
*/
public Employee getEmployeeById(Long id)
{
return (Employee)
getHibernateTemplate().load(Employee.class, id);
}

/**
* Save a Employee Object, if the given Employee
* is not in the data store,it should insert it,
* if it is in the data store, it should update it.
* @param employee
*/
public Employee saveEmployee(Employee employee)
{
getHibernateTemplate().saveOrUpdate(employee);
return employee;
}
}

3. Running the Example Application.

Now we are done with the spring configuration. We will write a client for Spring DAO now.
PersistEmp.java
--------------------------------

package com.ideeksha;


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

public class PersistEmp {

public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("spring2beans.xml");
EmployeeDAO dao=( EmployeeDAO)context.getBean("employeeDAO");
Employee emp = new Employee();
emp.setEmployeeName("Anil Verma");
dao.save(group);

}
}

Now we can run this client application directly. This will be the final spring conf file :
spring2beans.xml
-------------------------------
<!-- from the file 'context.xml' -->
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">


<bean id="employeeDAO" class="com.ideeksha.EmployeeDAOImpl">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/hibernate"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/ideeksha/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
</value>
</property>
</bean>
</beans>


And yes the last part remaining is the 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ideeksha</groupId>
<artifactId>SpringHibernate</artifactId>
<name>SpringHibernate</name>
<version>0.0.1-SNAPSHOT</version>
<description/>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.5.ga</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>

</project>



Check the database table, is your employee is been persisted or not ...If Yes ..I can say now you have successfully integrated hibernate and spring. If "No" ...Its time to go to bed ...try next morning :)


And off-course if you feel lazy to do the coding ...this is the link were you will get the code ..

http://www.mediafire.com/download.php?jydgwgmhynw

Cheers!!!

No comments :