Advertisement :
   Log In    OR    Register  
  Topics :  
RMI Example

Home >>> Hibernate Tutorial >>> Hibernate Transaction >>> Question
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 :
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...


Written By : Amit
Title :
Many to Many Mapping Example
Description : code
More...


Written By : Amit
Title :
Interview questions answer
Description : discussion
More...


Written By : Amit
Title :
Interceptor use log SQL statements
Description : example code
More...


Written By : Amit
Title :
Class Hierarchy Persist example
Description : code
More...

Tags/Keywords : Hibernate Transaction,Hibernate, TransactionQuestion
Author : guddu
Date (Year/Month/Date): 2009-04-15 Using JDBCTransaction with Hibernate ContextualSession Question For a command line based application on Java Technology, I would like to use JDBC Transaction and create a contextual Hibernate Session and I should be able to retrieve Hibernate Session from SessionFactory by using getCurrentSession() method?? Can anyone please help me in creating an 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.

Hibernate Transaction - In this example, we shall see how to use JTA along with Hibernate Session, while using JBoss as application server. By creating a SessionBean that is configured as stateless, and using DAO for Hibernate related Session handling.
Advertisement :
Software environment used in this example are as follows: 1. JDK 1.5.x 2. Eclipse 3.2 3. MySQL 5.0 4. Hibernate 3.2 5. JBoss 4.0.5 This example tries to demonstrate a practical approach to handling JTA transaction from Application server container managed transaction to be used along with Hibernate Session, without really creating separate Hibernate Transaction, thus avoiding need for managing any explicit Transaction in code, like begin transaction, commit and rollback Hibernate transaction. By using Container Managed Transaction, I think, there would be virtually no need for programmer to manage Hibernate transaction and Session flushing and closing activities and related coding, instead Application server container handles transaction and with transaction being associated with Hibernate session, session will eventually flushed and closed, appropriatly. This example can be configured in Eclipse 3.2 workspace, as a Java Project. This is the way I always use to start with any case study, making my life simpler with many features of Eclipse helping me with coding, compiling, building, and running Java command line based Test Client/Code. Example Case study: Account information of an individual is to be persisted into database. Account has following information such as account number, holder name, account type, account status whether active or not active. Account.java
package example.businessobject;

import java.io.Serializable;

public class Account implements Serializable {
  private String accountNumber;
  private String holderName;
  private String accoutType;
  private boolean accountActiveStatus;
  
  public boolean isAccountActiveStatus() {
	return accountActiveStatus;
  }
  public void setAccountActiveStatus(boolean accountActiveStatus) {
	this.accountActiveStatus = accountActiveStatus;
  }
  public String getAccountNumber() {
	return accountNumber;
  }
  public void setAccountNumber(String accountNumber) {
	this.accountNumber = accountNumber;
  }
  public String getAccoutType() {
	return accoutType;
  }
  public void setAccoutType(String accoutType) {
	this.accoutType = accoutType;
  }
  public String getHolderName() {
	return holderName;
  }
  public void setHolderName(String holderName) {
	this.holderName = holderName;
  }
}
Related database table creation script is as follows: (MySQL 5.0 as database)
create table account_info 
(account_number varchar(100) not null primary key, 
 holder_name varchar(100), account_type varchar(100),
 account_active_status integer(1));

Mapping HBM file showing the Entity "Account" being mapped with the database table "account_info"; as follows: Account.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.businessobject">
  <class name="Account" table="account_info">
    <id name="accountNumber" access="property" 
                             column="account_number"/>
    <property name="holderName" access="property" 
                                column="holder_name"/>
    <property name="accoutType" access="property" 
                               column="account_type"/>
    <property name="accountActiveStatus" access="property" 
                      column="account_active_status"/>
  </class>
</hibernate-mapping>
Follwoing Class diagram shows how application specific DAO has used Hibernate SessionFactory and all the methods from HibernateDAO can be inherited by the example specific DAO and at the same time all the example business specific methods are realized from the ExampleDAO interface. Following Sequence diagram shows, how the method invocation from the Example specific Facade (Session Bean), to the example DAO classes. ExampleFacade.java
package example.facade;

import java.rmi.RemoteException;

import javax.ejb.EJBObject;

import example.businessobject.Account;

public interface ExampleFacade extends EJBObject {
    public String createAccount(Account account) 
	                                   throws RemoteException;
    public void manageAccount(Account account) 
	                                   throws RemoteException;
    public void deleteAccount(Account account) 
	                                   throws RemoteException; 

}
ExampleFacadeBean.java (Please bear with some of the violation of common coding standard best practices.)
package example.facade;

import java.rmi.RemoteException;

import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

import example.businessobject.Account;
import example.exception.AccountException;
import example.service.AccountService;

public class ExampleFacadeBean implements SessionBean {
  private SessionContext ctx;
    public String createAccount(Account account) throws RemoteException
    {
    	String acctNumber = null;
    	System.out.println("$$$$$$$$$$inside sessionbean");
    	try {
    		acctNumber =  new AccountService().createAccount(account);
		} catch (AccountException e) {
			e.printStackTrace();
		}
		return acctNumber;
    }
....
....
}
As you can notice in sequence diagram, this Facade bean is calling AccountService.createAccount method. AccountService.java
package example.service;

import example.businessobject.Account;
import example.dao.AccountDAO;
import example.dao.DataAccessException;
import example.exception.AccountException;

public class AccountService {
  public String createAccount(Account account) throws AccountException {
	  String acctNumber;
	  try {
		  acctNumber = new AccountDAO().save(account);
	} catch (DataAccessException e) {
      throw new AccountException(e);
	}
	return acctNumber;
  }
}
Now AccountService is calling AccountDAO.save method. AccountDAO.java
package example.dao;

import example.businessobject.Account;

public class AccountDAO extends HibernateDAO implements ExampleDAO {
    
	public void delete(Account account) throws DataAccessException {
		deleteObject(account);
	}

	public String save(Account account) throws DataAccessException {
		return (String) saveObject(account);
	}

	public void update(Account account) throws DataAccessException {
		updateObject(account.getAccountNumber(), account);
	}

}
AccountDAO has method implementation of all the method definition from ExampleDAO, and each of these methods are using proper inherited methods from HibernateDAO class, like save method in AccountDAO is using saveObject method from the super class HibernateDAO.saveObject. HibernateDAO class is using a Singleton class SessionFactoryProvider for getting Hibernate SessionFactory implementation. HibernateDAO.java
package example.dao;

import org.hibernate.SessionFactory;

public class HibernateDAO {
  private SessionFactory sessionFactory = SessionFactoryProvider
                              .getInstace().getSessionFactory();
  protected Object saveObject(Object obj) {
	return sessionFactory.getCurrentSession().save(obj);
  }
  protected void updateObject(String id, Object obj) {
	  sessionFactory.getCurrentSession().update(id, obj);
  }
  protected void deleteObject(Object obj) {
	  sessionFactory.getCurrentSession().delete(obj);
  }
}
As SessionFactory from Hibernate can be a single instance serving multiple request from multiple clients, so can be created once and be used from a Singleton class / implementation. SessionFactoryProvider.java
package example.dao;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionFactoryProvider {
  private final static SessionFactoryProvider sessionfactoryProvider = new SessionFactoryProvider();
  private SessionFactory sessionFactory;
  private SessionFactoryProvider() {
	  try {
		  sessionFactory = new Configuration()
		               .configure("config/hibernate.cfg.xml")
					   .buildSessionFactory();
	  } catch (HibernateException ex) {
		  ex.printStackTrace();
	  }
  }
  public static SessionFactoryProvider getInstace() {
    return sessionfactoryProvider;
  }
  public SessionFactory getSessionFactory() {
	  return sessionFactory;
  }
}
After setting up complete environment for this example in an workspace created using Eclipse, following are the list of some of the files used in this example, as follows: If you are interested in looking at most of the other files from the complete source code, then you may have to be logged in. Please be informed that these files are for read only purpose, and copying is disabled.
Login / Register

Advertisement :


	

Commented By ->
Amit
I guess, you can define JDBCTransaction in Hibernate configuration file
for following properties in session-factory tag :
        <property name="hibernate.transaction.factory_class">
		             org.hibernate.transaction.JDBCTransactionFactory
		</property>
        <property name="hibernate.current_session_context_class">managed</property>

and by using ManagedSessionContext and by binding Hibernate Session to it,
thus one can obtain current Hibernate Session and should be able to use
getCurrentSession from SessionFactory Object.

Commented By ->
Amit
Can anyone explain how to use JTA transaction with Hibernate
SessionFactory,while the business tier has Stateless
SessionBean and Persistence layer has DAO with Hibernate as
ORM tool??

I am using JBoss 5.0.0 Beta2 AS Application server.

Commented By ->
B.Veera Lava Kumar Reddy
Its really Nice example, could u please send soruce code.

Regards
Lava Kumar

Commented By ->
Rajan
Hi

Thanks. This example helped me to understand the
basics of as how JTA can be used,I am new to 
hibernate and need some more information about
the above example specially configuration and 
entries required for hibernate config file to 
run a Hibernate JTA Transaction based 
application.It would be helpful if you can 
suggest the needful. I am using the above said 
software environment itself.

Regards
Rajan

Commented By ->
tom
it is very good. i want to know how to integrate 
JTA with hibernate in hibernate config file.
could you send source code to me

Commented By ->
Nithin Kongadan
its realy very good and usefull example , pls send the config file for the use JTA , is it sever dependent?

Commented By ->
Karthik
Hi.I am new to hibernate.I want to know how we 
can use JTA transaction based.Could you send 
source code for me.

Commented By ->
guddu
As I have received many request for source code for this example,
I have decided to provide it with a precondition so as to be 
able to see this only after log in and on this page only.

As this example is having a server component and doesn't have
a WAR file, so the compiled code can be placed in a JAR file,
and deployed onto the JBoss Application server version 4.0.5
(as I have tested this in this version only. It may work in 
other versions of JBoss application server as well).

Hope this helps.

Commented By ->
Ritesh Seth
Can you please guide on how to use JTA transaction with Hibernate, I have a sample scenario whereby there
is
 programmatic Transaction handling within code and I wanted to
use the same global transaction across all Hibernate related
database operations, this means I am trying to use the programmatic Transaction along with the Hibernate
Session.

Any help would be highly appreciated!!!

Commented By ->
guddu
I tried just to understand the behavior of Hibernate Transaction
when the session bean from this example is initiating a
bean managed transaction.So I have modified some of the files
and to my utmost delight, I observed that I had to change
only two files, such as the Session bean implementation
class and the ejb-jar.xml descriptor file.

Modification those are done on these two files are to initiate
a UserTransaction from the Session Bean and to propagate it
to the Hiberate's contextual session.

So there is no need to have transaction related coding within
DAO and with Hibernate's method calls.

The Session bean is having lookup code for getting 
UserTransaction and executing begin, commit/rollback methods
on the existing JTA transaction.

ExampleFacadeBean.java
-----------------------------
package example.facade;

import java.math.BigDecimal;
import java.rmi.RemoteException;

import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import example.businessobject.Account;
import example.exception.AccountException;
import example.service.AccountService;
import example.service.BusinessException;
/**
 *  This is provide AS IS without any Guarantee of any kind
 *  Author: Guddu from IQTF
 *  Date: 15th April 2009
 */
public class ExampleFacadeBean implements SessionBean {
  private SessionContext ctx;
    public String createAccount(Account account) throws RemoteException
    {
        String acctNumber = null;
        System.out.println("$$$$$$$$$$inside sessionbean");
        UserTransaction trans = null;           
        try {
            trans = (UserTransaction) ctx.lookup("UserTransaction");
            trans.begin();
                
            acctNumber =  new AccountService().createAccount(account);
            trans.commit();
        } catch (AccountException e) {
            e.printStackTrace();
        } catch (NotSupportedException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (RollbackException e) {
            e.printStackTrace();
        } catch (HeuristicMixedException e) {
            e.printStackTrace();
        } catch (HeuristicRollbackException e) {
            e.printStackTrace();
        }
        return acctNumber;
    }
    public void manageAccount(Account account) throws RemoteException 
    {
        
    }
    public void deleteAccount(Account account) throws RemoteException 
    {
        
    }
    public boolean transferAmount(Account acc1, Account acc2, BigDecimal amt)
                                               throws RemoteException {
        boolean status = false;
        UserTransaction trans = null;
        try {
            trans = (UserTransaction) ctx.lookup("UserTransaction");
            trans.begin();
            status = new AccountService().tranferAmount(acc1, acc2, amt);
            trans.commit();
        } catch (BusinessException e) {
           try {
               trans.rollback();
           } catch (IllegalStateException e1) {
               e1.printStackTrace();
           } catch (SystemException e1) {
               e1.printStackTrace();
           }
             status = false;
             throw new RemoteException("Some Exception Happened",e);
           } catch (SecurityException e) {
             e.printStackTrace();
           } catch (RollbackException e) {
             e.printStackTrace();
           } catch (HeuristicMixedException e) {
             e.printStackTrace();
           } catch (HeuristicRollbackException e) {
             e.printStackTrace();
           } catch (SystemException e) {
             e.printStackTrace();
           } catch (NotSupportedException e) {
             e.printStackTrace();
           }
            return status;
    }

        public void ejbCreate() throws EJBException, RemoteException {
                // TODO Auto-generated method stub

        }

        public void ejbActivate() throws EJBException, RemoteException {
                // TODO Auto-generated method stub

        }

        public void ejbPassivate() throws EJBException, RemoteException {
                // TODO Auto-generated method stub

        }

        public void ejbRemove() throws EJBException, RemoteException {

        }

        public void setSessionContext(SessionContext arg0) throws EJBException,
                        RemoteException {
          this.ctx = arg0;
        }

}
ejb-jar.xml .... .... <transaction-type>Bean</transaction-type> .... .... Intention of this program is to demonstrate some of the specific coding stuff related to Transaction handling only, so one can find many places where code improvement is required.
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: *
36,26
Enter bigger number from above :*
Home >>> Hibernate Tutorial >>> Hibernate Transaction >>> Question
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 *:
40,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.