Home >> Spring Framework
Spring Hibernate Example
In this page I am going to explain a very simple (at least I think so)
yet practical approach for solving a typical problem of associating /
using Spring with Hibernate.
For those of you, who have already used Hibernate along with Data
Access Object design pattern in Persistence Layer, I think you should agree
to the fact that JTA transaction can be mentioned in hibernate
configuration cfg XML file and to be loaded by using Configuration
and buildSessionfactory method provided by Hibernate Framework API.
|
|  |
|
Properties of Hibernate SessionFactory can be defined using
programmatically, by using methods of Configuration, or by defining
hibernate configuration file.
While using Spring for loading appropriate Beans, like one bean definition for
Data source, one bean definition for Transaction, one bean definition for
Session Factory, by this one can easily de-couple dependencies from application
specific classes or architectural layers/modules boundaries.
For example, in case of DAO (Data Access Object), without using Spring,
one has to extend Hibernate specific classes/interfaces in DAO classes
directly and this makes application DAO rather tightly integrated to
Hibernate and requires code changes if in future, project architecture
demands additional or some other type of ORM tool to be inducted.
With Spring's Dependency Injection, it is like providing or instantiating
appropriate object and provide it as a bean to the actual user/class.
Like for example, if project requires an additional data source in terms
of calling web service and receiving feeds apart from using existing
Database, then in my thinking the DAO layer has to change to accommodate
this new requirement/web service based data source, if DAO is directly
handling Hibernate specific dependencies.
But with Spring, it requires addition or modification in configuration
file so as to be able to inject appropriate data source (be it Hibernate
or web service), on demand.
Once we see some of the example of both these type of implementations,
this will be even much clearer.
While using Spring Framework, there is a dependency to the way we define Beans.
With Spring Framework, all the beans, those are configured in Spring related
configuration files, has to be instantiated by Spring framework only,
and one has to retrieve these beans from Spring Framework classes like
all concrete classes those implementing
org.springframework.beans.factory.BeanFactory interface from Spring,
such as XmlWebApplicationContext (in case of web based application),
FileSystemXmlApplicationContext (any Java based application which
has an access to local file system), ClassPathXmlApplicationContext
(resource or con fig file from class path) and many more.
So I can say Dependency Injection with Dependency to Spring.
So, I think, uses of Spring can become very much necessary when there
are many changes or plug and execute kind of implementation is desirable
in project/product.
Now coming back to the example, here I am going to explain an example
on how I have used Spring and Hibernate in a web based application.
Example Environment used:
1. JDK 1.5
2. JBoss 5.0.0 Beta2
3. Spring Framework 1.2.8
4. Hibernate 3.2
5. Eclipse 3.2
6. MySQL 5.0
As usual, I guess , setting up all the above software is left to each
individual preferences.
Steps include:
1. Setting up Eclipse workspace.
2. Creating a Java project with appropriate name.
3. Creating a source folder and appropriate packages.
4. Creating a separate folder for JSP files.
5. Creating WEB-INF, WEB-INF\lib and WEB-INF\classes folders.
6. Creating WEB-INF\config\hibernate-config and
WEB-INF\config\spring-config for keeping Hibernate and Spring specific
configuration files, respectively.
7. Setting appropriate source folder in Project->Properties->Java Build Path
->Source tab->Add Folder and the Default output folder:
Project/WEB-INF/classes folder, in order to place all compiled class
files of source folder to this destination folder, and by this way
following/adhering to the WEB application packaging hierarchy.
8. Adding appropriate JAR files, in my example I have used
minimum functionality, so minimum set of Jar files place in WEB-INF/lib
folder, such as JAR file from Spring Framework, Hibernate, and dependent
JAR files like :
antlr-2.7.6.jar
asm.jar
asm-attrs.jar
cglib-2.1.3.jar
This example is very simple, as follows:
There will be a screen for user to enter certain test values, and these
values will be persisted to database table.
But I am emphasizing on setting up environment for using Spring for
providing Hibernate SessionFactory to the DAO class implementation.
Appropriate Spring configuration file is loaded by using either Spring
Context Listener (org.springframework.web.context.ContextLoaderListener)
or Spring context servlet (org.springframework.web.context.ContextLoaderServlet)
and for loading appropriate applicationContext.xml file, there is certain
tags like context-param with appropriate param name and param value pair are
used, as shown below:
web.xml
....
....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/spring-config/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- OR
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
-->
....
....
This applicationContext.xml file uses appropriate configuration for datasource,
Hibernate Sessionfactory with Hibernate properties settings.
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="myDataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:MysqlDS"/>
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>/WEB-INF/config/hibernate-config/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</prop>
<!--
<prop key="hibernate.transaction.manager_lookup_class">
org.hibernate.transaction.JBossTransactionManagerLookup
</prop>
<prop key="jta.UserTransaction">UserTransaction</prop>
-->
</props>
</property>
</bean>
</beans>
Corresponding Hibernate config file
/WEB-INF/config/hibernate-config/User.hbm.xml
in this example, is as simple as follows:
User.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.i2w.domain">
<class name="User" table="User" lazy="true">
<id name="id" access="property"/>
<property name="name" access="property"/>
</class>
</hibernate-mapping>
There are many ways one can retrieve Hibernate SessionFactory,
one of the way I choose for this example, is by providing a Servlet
that loads on web server start up, and provides SessionFactory as
defined in applicationContext bean, from WebApplicationContext
as follows:
SessionFactoryProviderServlet.java
/**
* Provides SessionFactory for the application
*/
package com.i2w;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import org.hibernate.SessionFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.i2w.util.SessionFactoryProvider;
/**
* @author Amit
*
*/
public class SessionFactoryProviderServlet extends HttpServlet {
SessionFactoryProvider sessFact = SessionFactoryProvider.getInstance();
public void init(ServletConfig cfg)
{
WebApplicationContext webCtx = WebApplicationContextUtils
.getWebApplicationContext(cfg.getServletContext());
sessFact.setSessionfactory((SessionFactory)webCtx
.getBean("mySessionFactory"));
}
}
and corresponding entry in web.xml file is as follows:
<servlet>
<servlet-name>sessionfactoryprovider</servlet-name>
<servlet-class>com.i2w.SessionFactoryProviderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
So SessionFactoryProvider, a singleton class holds Hibernate Specific
one time created SessionFactory for this example, and can be used
as and when required in this example classes.
I have not provided complete source as it is, but in bits and pieces
for our interested visitor/reader to create this example and see it
running as desired.
Your feedback and comments will be a great help to the Author for
improvement (if any).
If you like to share your comment/suggestions/feedback relating to this Page,
you can do so by droping us an email at
usingframeworks @ gmail . com
with the subject line mentioning URL for this Page (i.e,
/spring-hibernate-example.php) or use this
LINK.
As per this website's privacy policy, we never disclose your email id,
though we shall post your comments/suggestions/feedback with
your name (optional) and date on this Page. If you don't want your
comments/suggestions/feedback to be shared in this Page, please
mention so in your email to us. Thank you very much.....
If anything missed out , please let me know at
techienjoy at yahoo . com