Advertisement :
   Log In    OR    Register  
  Topics :  
RMI Example

Home >>> Hibernate Tutorial >>> Spring Hibernate Integration example >>> Example
Struts Tutorials:
Struts2 Tag CheckBoxList
, Checkbox, Iterator, IF
Struts2 Tag Library Example Struts2 Tiles Example Struts2 Tiles I18N Example Struts2 Questions Struts Tiles I18N Example Struts Eclipse MVC Struts2 Tags Struts2 Example and Tutorial Struts MVC Struts2 Validation
Hibernate Tutorials: Hibernate Case Study Class Hierarchy Persist Example Using Hibernate Interceptor Hibernate Questions with Answer Hibernate Many-to-Many Mapping Example Hibernate one-to-many Mapping Example Hibernate and ORM tools Spring Hibernate Example Hibernate SessionFactory Example Hibernate Mapping Class Hierarchy Hibernate Questions Hibernate SessionFactory Questions Spring Hibernate Example: Spring Hibernate Case Study

Written By : Amit
Title :
Interview Questions
Description : On Hibernate
More...


Written By : Amit
Title :
mapping class hierarchy table per subclass
Description : Example
More...


Written By : Amit
Title :
ways create Hibernate SessionFactory
Description : Example
More...


Written By : Amit
Title :
Spring Hibernate Integration example
Description : Example
More...


Written By : Amit
Title :
ORM Hibernate Best FIT
Description : Discussion
More...


Written By : Amit
Title :
One to Many mapping example
Description : Code
More...

Tags/Keywords : Spring Hibernate Example, Spring, Hibernate, Example, Code, Tutorial, Article
Author : Amit
Date (Year/Month/Date): 2009-02-18 SpringFramework and Hibernate Integration an example discussed

Please be informed that NONE of the design/code from this
page is claiming to be some sort of best practices and we DO NOT expect
any of our visitor/reader of this page to assume this as some sort of
best practice for any context and should not be using this 
as it is without appropriate evaluation to their, so to say, 
specific programming context.

This page intends only to provide bit and piece of known ways  for
doing some sort of example and may not be fit for any other purpose.

I have spend many hours in understanding how I think can be
a way of setting up Spring and Hibernate using JBoss
application server, in my small local development environment.

Advertisement :
I have tried my ways and means of arranging for required software and start this demonstration quickly. My Software environment for this example: 1. Eclipse 3.2 2. JDK 1.5 3. Hibernate 3.2 4. SpringFramework 1.2.8 5. MySQL database 5.0 6. JBoss 5.0.0 Beta2 Objective of this exercise is to use application server JTA transaction along with Spring and Hibernate, and EJB. So idea is to create an EJB session bean, and configuring Spring and Hibernate to as to be able to use the Container Managed Transaction initiated by the client requesting session bean, to Spring BeanFactory to get the Hibernate SessionFactory created. Using this SessionFactory, and Session, I should be able to do a simple JDBC insert operation on database table. In this way JTA transaction actually initiating Session, throughout the complete lifecycle of Session bean transaction begin and commit /rollback and this operation is getting automatically rolled back in case of any exception raised in Database. Steps I followed are as follows: 1. Created a workspace in Eclipse. 2. Created a Java project. 3. Created a source folder. 4. Now using my prior experience of creating Session bean in JBoss. (If anyone interested in learning how to use XDoclet 1.2.3 to create JBoss Session Bean EJB3.0 , using annotation, then I shall be writing an article on this topic as well. Keep visiting for updates) 5. Created a DAO class for hiding all Hibernate SessionFactory and Session related operation insulated from the Session Facade. 6. Now, most important part is, defining applicationContext.xml file using SpringFramework. 7. My configuration is defined in applicationContext.xml file as follows:
<?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>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.current_session_context_class">
	  jta
	</prop>
	<prop key="hibernate.transaction.factory_class">
	    org.hibernate.transaction.JTATransactionFactory
	</prop>
	<prop key="hibernate.transaction.manager_lookup_class">
	    org.hibernate.transaction.JBossTransactionManagerLookup
	</prop>
	<prop key="jta.UserTransaction">UserTransaction</prop>
  </props>
 </property>
</bean>
</beans>
This applicationContext.xml file is pretty much self explanatory. First part is the way I defined the DataSource, and the SessionFactory. SessionFactory has various Hibernate properties for setting up JTA Transaction, with the help of JBossTransactionManagerLookup and JTATransactionFactory. Current session context is defined as "jta", for the Hibernate session to be initiated during the JTA Transaction startup. And there is no need for the developer to open and close/flush Hibernate Session in code. Instead, one has to just use the getCurrentSession for getting the same session throughout the complete transactional operation. jta.UserTransaction, is looking up the JNDI UserTransaction of the application server for using it in JTA. Now one very important question is: How to get a handle of Hibernate SessionFactory in EJB code/ DAO? I have used a Singleton class for looking loading applicationContext.xml file and getting the SessionFactory as a Bean from the Spring BeanFactory. This Singleton class is very inserting to see and is as follows:
/**
* This code is provided "AS IS".
*
*/

import javax.transaction.Transaction;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SessionFactoryProvider
{
	private SessionFactory sessFactory;
	private Transaction userTrans = null;
	private final static SessionFactoryProvider sessFactProvider
                                          = new SessionFactoryProvider();
	private SessionFactoryProvider()
	{
         ClassPathXmlApplicationContext appContext =
			  new ClassPathXmlApplicationContext(
                               new String[] {"applicationContext.xml"});
        BeanFactory factory = (BeanFactory) appContext;
        sessFactory = (SessionFactory)factory.getBean("mySessionFactory");
	}
	public static SessionFactoryProvider getInstance()
	{
		return sessFactProvider;
	}
	public SessionFactory getSessionFactory()
	{
		return this.sessFactory;
	}
}
If this Singleton class is loaded for the first time, the it creates SessionFactory for one time only, and returns SessionFactory, on request using getSessionFactory(). I have chosen to instantiate Singleton class in ejbCreate lifecycle method of the Session bean, so as to have the SessionFactory created before any business method invocation: public void ejbCreate() throws CreateException { SessionFactoryProvider.getInstance(); } Having written all these, I wanted your thinking about a particular scenario where by I am not being able to execute this code from a WAR file. Same applicationContext.xml file when used in a web application and loaded using context loader listener/Servlet, I was getting a ClasscastException for the Transaction part while Hibernate SessionFactory is getting loaded/instantiated. I think, I am not sure, but it could be due to the JDBCTransaction getting initiated instead of JTA transaction in Web application and in WAR file. Did anybody encountered this kind of exception? do write your experience to me By Replying to this writing.
Advertisement :
Author of this article/writeup has expressed his/her willingness
to help or guide users with any technical difficulties he/she faces while working with the example code environment setting up, running and resolving any such exception raised during compile or at runtime. You may ask for any technical doubt or seek technical help related to this article by using following form to reach for technical help from the Author for FREE. This article's Author shall be reading your request and responding within reasonable time (no resolution timeframe defined as such).


	
 
Replied By ->
Amit
<?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>

here I pasted the User.hbm.xml file that I used in this example.
 
 
Replied By ->
Amit
<?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>

as shown above , by removing manager look up class and jta UserTransaction, and providing
JDBCTransactionfactory in place of JTATransactionfactory for the hibernate.transaction.factory_class.
This web application can now use JDBC Transaction and the class cast eception is not occurring now.
 

Commented By ->
Guddu
Can you post stack trace of exception that you say you are getting?

Because, I have recently set up the exact same environment
as per you in this Page, but it is working for me and I
am not getting any exception, and it is working fine.

After looking at the Exception, I may be able to help.

One Change I have made is the JNDI name of the datasource
as java:MysqlDS instead of java:/MysqlDS.
And can you paste the User.hbm.xml file for me to look at it?

Commented By ->
Amit
I guess, the issue we are discussing out here is that
how to make use of JTA transaction in a WAR archive file/web application.

To my understanding, when JTA transaction configuration done for 
EJB module/application, it worked fine, as the EJB application JAR is 
getting deployed in APP/EJB container, but when a WAR file
is deployed onto a web container, then absense of default 
JTA implement throws related exception.

Has anyone ever used any plugin in Tomcat web server for running
JTA transaction in a web application.

Any sort of help will be highly appreciated...
Thanks in advance.

Commented By ->
good123
Hi Amit,

If you are looking specifically JTA implementation to work 
with Tomcat, then I suggest you to look or explore more on
JOTM and a reference documentation link
on how to
configure JOTM in Tomcat.
Hope this helps.

Commented By ->
Amit
1. Can anyone please provide me some example code on using Hibernate3
   DAO support feature from Spring Framework?

2. What are the difference between using Spring framework DAO Support
   like HibernateDaoSupport or creating application specific DAO
   for interacting with Hibernate?

3. What are the ways of using HibernateTemplate along with 
   HibernateDaoSupport from Spring framework?

Commented By ->
javed
Hello All,

Can any one tell me resource link for Spring hibernate integration with oracle database .I am not getting
exact xml (bean) configuration.

Commented By ->
Amit
Hi Javed,

To the best of my understanding on this topic,
Defining configuration file for Spring using the Oracle database as persistence
requires settings those can be very straight forward. One has to determine whether to
go for the Application server datasource or pure JDBC driver (Oracle JDBC Driver),
accordingly one has to define the applicationContext.xml file , and for using any
Oracle specific features, one may have to define appropriate Dialect as well.

As of now I don't see any other change required to run this sample/example
using Oracle database as persistence.

Thanks,
Amit

Commented By ->
Guddu
I think, while using Hibernate along with Spring one can use
some of the support classes from Spring Framework, such as
HibernateDAOSupport, HibernateTemplate etc. along with application
DAO class files in order to use some of the ready made 
handling of Hibernate Session along with already running Transactions (if any),
and of course managing those flush, close of related Hibernate Session 
will be automatic.

here is the link for the HibernateDAOSupport class from Spring.
http://static.springsource.org/spring/docs/2.0.8/api/org/springframework/orm/hibernate3/support/HibernateDaoSupport.html
Hope this helps.
Are you interested in solving a very interesting Technology Stack while Playing this Game          

Please write your Comment on this Matter
(This will be visible if found suitable):
Name: *
Email (will not be displayed): *
Matter: *
11,22
Enter bigger number from above :*
Home >>> Hibernate Tutorial >>> Spring Hibernate Integration example >>> Example
Visitor/User referred related external URL:
(Visible upon review and approved by this site Administrator)
Referred By Name *:
Resource URL *: (e.g, URL should be starting with http://www.-----.---)
 
Resource Short Description *:
26,19
Enter bigger number from above : *

Please log in to add or reply to any matter<- requires login
Log in or Register
Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
CONTACT    PRIVACY POLICY    DISCLAIMER
Terms of Use and Disclaimer :

This web site provides some of the information about various technologies, example 
code, tips, tutorials etc. Like any printed materials, content of these pages may 
become out of date over a period of time. Therefore all visitor/users of this web 
site are requested/advised to refer to the originating parties/sources for the 
latest changes and happenings for detailed information. This information is not 
intended to be a substitute for the original reference provided by the originating 
parties/sources.

By accessing and using this website in any ways, including, without
limitation, browsing the website pages, using any information, using any content and/or 
downloading any materials, you agree to and are bound by the terms of use 
described in this page and Usage Terms and Conditions. 
If you do not agree to all of 
the terms and conditions contained in the terms of use described in this
page and Usage Terms and Conditions, do not use this 
website in any manner. If you are using the website on behalf of your 
employer, you represent that you are authorized to accept these Terms of Use 
on your employer's behalf.

All Trademarks are property of their respective owner. Appropriate measure is being
taken for providing accurate and up-to-date information but like any printed materials,
these blog(s)/contents may eventually be outdated one day, so if you are using any 
of these information, please refer original content/documentation from respective sources. 
And under no circumstances shall the Author of these contents and/or this web site
be liable for any loss, damage, expense incurred or suffered which is claimed to have
occurred because of usage of the contents of this web site.
If you have any questions/queries/feedback/suggestions then please write to this web
site owner at contact.