Advertisement :
   Log In    OR    Register  
  Topics :  
RMI Example

Home >>> Spring Hibernate Example >>> Hiberate Spring Tutorial >>> Example code
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 : ISHTEK
Title :
Design Spring Hibernate
Description : Example Case study
More...


Written By : Amit
Title :
Hiberate DAOSupport
Description : Hiberate Template
More...


Written By : Amit
Title :
HiberateDAOSupport Example
Description : Design discussion
More...


Written By : guddu
Title :
JTA Transaction
Description : Using LocalSessionFactoryBean From Spring
More...

Tags/Keywords : Spring Hibernate Example,TutorialHiberate-Spring-Tutorial,Example-code
Author : Amit
Date (Year/Month/Date): 2009-03-27 Spring Hibernate Example

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.

Spring Hibernate Example

I am just going to explain a very simple, yet practical approach
to solving a typical problem of associating / using Spring with
Hibernate, how?
Those who have already used Hibernate along with Data Access Object
design pattern in Persistence Layer, should agree to the fact that
JTA transaction has to be mentioned in hibernate file and
to be loaded by using Configuration and buildSessionfactory method.

Advertisement :
Properties of Hibernate SessionFactory can be defined using programmatically methods of Configuration, or by defining hibernate file. While using Spring for loading appropriate Beans like one for Data source, one for Transaction, one for Session factory, one can easily de-couple dependencies from application specific classes or layers. 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, there is a dependency to the way we create Beans. With Spring, 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 we 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.
    Advertisement :
    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).
    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).
    
    
    	

    Commented By ->
    Amit
    In this Spring Hibernate example, if anyone can't use Servlet for loading
    BeanFactory (from Spring Framework) and getting SessionFactory (from Hibernate)
    , then there are some other work arround or method of getting desired Bean
    out of Spring Framework, for use in helper classes, such as 
    org.springframework.beans.factory.xml.XmlBeanFactory that implements 
    org.springframework.beans.factory.BeanFactory for Spring Framework
    to be able to load appropriate applicationContext.xml file and provides appropriate
    beans on request, in our example it is Hibernate SessionFactory.
    
    By modifying com.i2w.util.SessionFactoryProvider private constructor, and adding 
    following set of lines:
    
    BeanFactory beanFactory = new XmlBeanFactory(
                 new ClassPathResource("/WEB-INF/config/spring-config/applicationContext.xml"));
    this.sessFactory = (SessionFactory) beanFactory.getBean("mySessionFactory");
    System.out.println("SessionFactoryProvider is created.... ********" + sessFactory);
    
    
    makes this singleton, create BeanFactory and get bean from Spring BeanFactory,
    the most desirable Hibernate SessionFactory :)
    
    Rest of the code remains the same, and on submission of request from index.jsp,
    UserBean.createUser method calls SessionFactoryProvider and SessionFactoryProvider
    creates BeanFactory from the applicationContext.xml file, and getBean returns
    appropriate SessionFactory of Hibernate. Thus UserBean helper class uses 
    Hibernate Session and saves this record User to database table.
    
    The difference from the earlier Servlet approach was that, applicationContext.xml
    file was getting loaded by the Spring context Listener or Spring context Servlet,
    and the application Servlet uses ServletContext to get appropriate BeanFactory and 
    then appropriate SessionFactory Bean. In this approach, SessionFactory is getting load on
    first call for the Singleton class that is SessionFactoryProvider class.
    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: *
    38,16
    Enter bigger number from above :*
    Home >>> Spring Hibernate Example >>> Hiberate Spring Tutorial >>> Example code
    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 *:
    7,15
    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.