Advertisement :
   Log In    OR    Register  
  Topics :  
RMI Example

Home >>> Hibernate Tutorial >>> Contextual Session >>> Example Case study
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 : Hibernate Session,Contextual-Session,Example-Case-study
Author : Amit
Date (Year/Month/Date): 2009-04-18 Example showing ManagedSessionContext
Example on using Hibernate JDBCTransaction and current session API for 
using a single Hibernate Session and JDBCTransaction from
managed as current_session_context_class and using Hibernate
ManagedSessionContext .

A very simple commandline based Java application, that uses a configuration
XML file (example.xml) to read all properties for creation of SessionFactory,
and a HBM XML file for mapping a class (example.User) to persistent Table "User".

example.xml
tr>
<?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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">
                  org.hsqldb.jdbcDriver
        </property>
        <property name="connection.url">
                  jdbc:hsqldb:hsql://localhost
        </property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- SQL dialect -->
        <property name="dialect">
                  org.hibernate.dialect.HSQLDialect
        </property>

        <!-- Enable managed session context management -->
        <property name="transaction.factory_class">
                  org.hibernate.transaction.JDBCTransactionFactory
        </property>
        <property name="current_session_context_class">
                  managed
        </property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

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

    </session-factory>

</hibernate-configuration>
Advertisement :
This example.xml file will be read by the TestClient main program and build Hibernate SessionFactory as shown below: example.TestClient.java tr>
package example;
import org.hibernate.*;
import org.hibernate.engine.*;
import org.hibernate.cfg.*;
import org.hibernate.context.*;
public class TestClient
{
SessionFactory sessFactory;
Session session;
public TestClient() {
    try{
        Configuration conf = new Configuration();
        sessFactory = conf.configure("example.xml").buildSessionFactory();
	//ManagedSessionContext is created
	//by using SessionFactoryImplementor
        ManagedSessionContext managedSession = 
	  new ManagedSessionContext((SessionFactoryImplementor)sessFactory);
	//Hibernate Session is opened and
	//bound to the ManagedSessionContext
        managedSession.bind(sessFactory.openSession());

        //From ManagedSessionContext a Hibernate
	Session can be obtained by using currentSession
        session = managedSession.currentSession();
        session.beginTransaction();
        User user = new User();
        user.setUserId("100C");
        user.setName("created");
        saveUserInfo(user);
        user.setName("modified");
        updateUserInfo(user);
        session.getTransaction().commit();
    } catch (Exception ex) {
        session.getTransaction().rollback();
        ex.printStackTrace();
    } finally {
        session.close();
    }
}
   /**
    *  Method that uses SessionFactory getCurrentSession 
    *  to persist User into database table.
    */
    public void saveUserInfo(User argUser) {
        Session localSession = sessFactory.getCurrentSession();
        System.out.println(localSession.getTransaction());
        localSession.save(argUser);
    }
    public void updateUserInfo(User argUser) {
        Session localSession = sessFactory.getCurrentSession();
        System.out.println(localSession.getTransaction());
        localSession.update(argUser);
    }
    public static void main(String[] args) 
    {
        new TestClient();
    }
}
All supporting information for storing User object to User table are listed below:
SQL
create table User
(user_id varchar(100), user_name  varchar(100), primary key(user_id));

example.User
package example;

public class User
{
	private String userId;
	private String name;
    public void setUserId(String argUserId) {
		userId = argUserId;
	}
	public String getUserId() {
		return userId;
	}
	public void setName(String argName) {
		name = argName;
	}
	public String getName() {
		return name;
	}
}


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="example">
  <class name="User" table="User">
        <id name="userId" access="property" column="user_id"/>
        <property name="name" column="user_name"/>
  </class>
</hibernate-mapping>

After going through the TestClient, one can very well understand objective of this example. Let me explain a bit: 1. current_session_context_class as "managed" and ManagedSessionContext provides a way to use getCurrentSession method of Hibernate SessionFactory in this Java command line application. 2. So JDBCTransaction has to be started/begin at some point of time, and will be available in two operations, such as saveUserInfo and updateUserInfo. 3. Once transaction is committed or rollback, Hibernate Session will be flushed. In finally block, Hibernate Session is closed. This example is trying to show a simple way to use Managed Session context with a JDBCTransaction and using a single Session and Transaction for multiple operations in form a single block of task. After compiling and running this TestClient, following is the output on console:

org.hibernate.transaction.JDBCTransaction@a761fe
org.hibernate.transaction.JDBCTransaction@a761fe
Hibernate: insert into User (user_name, user_id) values (?, ?)
Hibernate: update User set user_name=? where user_id=?
This output show that same JDBCTransaction is being used in both the operations, as the System.out.println for the Transaction, comes out to be same. Any questions from reader will be highly appreciated, and I would like to discuss more on improving this example with your suggestions. Thanks for reading this example.
Advertisement :


	
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,27
Enter bigger number from above :*
Home >>> Hibernate Tutorial >>> Contextual Session >>> Example Case study
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 *:
14,34
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.