Tech I Enjoy Logo

Custom Search




  Home >> Hibernate


Hibernate Transaction -
In this example, we shall see how to use Container Managed Transaction
from within JEE Container, 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.

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.


If anything missed out , please let me know at techienjoy at yahoo . com
Hibernate Join Example :
Using Table join explained with an example
while using Hibernate Framework.
Hibernate Component Property :
Hibernate Example on Component 
with source code explained.
Hibernate Transaction on JBoss :
Explaining Transaction using Hibernate
on JBoss Application Server.
Hibernate Example on composite Primary key :
Example on using Hibernate Framework
to work with mapping using composite
Primary key.
Hibernate Interview Questions :
Interview Questions on Hibernate with answer.
Hibernate class heirarchy mapping :
Hibernate Example on mapping
class hierarchy using various ways
of persisting into database
tables.
Hibernate Many to Many Mapping Example :
Many to many mapping example using Hibernate
Framework and a simple to follow steps.
Example on persisting Class Hierarchy :
Example on using Hibernate Framework
to persist Class Hierarchy into database.
Hibernate Named Query Example :
Named Query markup using an example
and Hibernate Framework.
Hibernate Bag Mapping Example :
class mapping using Bag Tag example using Hibernate
Framework and a simple to follow steps.
Hibernate Insert Update control :
Hibernate Example on controlling
insert and update attributes
List of Examples on Hibernate :
List of example using Hibernate.
Hibernate Interceptor Example :
Example on using Interceptor using Hibernate Framework
with source code explained.
Hibernate one to one mapping Example :
one to one mapping explained using an example
and Hibernate Framework.
Hibernate Example on Filter Criteria :
Example on using Filter Criteria
using Hibernate Framework to work with.
Class Hierarchy Mapping Example :
class hierarchy mapping example using Hibernate
Framework and a simple to follow steps.
Hibernate Example on Filter :
Example on using Filter using Hibernate Framework
to work with.
Hibernate one to many mapping Example :
one to many mapping explained using an example
and Hibernate Framework.
Hibernate one to many mapping Example :
one to many mapping explained using an example
and Hibernate Framework.
Hibernate Property Formula :
Hibernate Example on Property
Tag with ease to do code walk-through


References :
Tags: Hibernate Class Hierarchy Persist example
Tags: Hibernate composite primary key
Tags: Hibernate criteria filter example
Tags: Hibernate Filter Example
Tags: Hibernate Interceptor example
Tags: Hibernate Interview Questions
Tags: Hibernate join example
Tags: Hibernate Many to Many Mapping Example
Tags: Hibernate mapping bag
Tags: Hibernate mapping class hierarchy table per subclass
Tags: Hibernate named query markup
Tags: Hibernate One to Many mapping example
Tags: Hibernate One To One Mapping Example
Tags: Hibernate scenario one to many
Tags: Hibernate transaction jboss
Tags: Hibernate



DISCLAIMER :
The content provided in this page is not warranted and/or guaranteed by techienjoy.com. 
techienjoy.com is not liable for any negative consequences that may result/arise from 
implementing directly/indirectly any information covered in these pages/articles/tutorials.

All contents of this site is/are written and provided on an "AS IS" basis,
without WARRANTIES or conditions of any kind, either express or implied, including, without
limitation, merchantability, or fitness for a particular purpose. You are solely responsible
for determining the appropriateness of using or refering this and assume any risks associated
with this.

In spite of all precautions taken to avoid any typo in these pages, there might be some 
issues like grammatical mistakes and typos being observed in these pages, techienjoy.com
extends sincerest apologies to all our visitors for the same.



Android Examples || Android Examples

© Copyright 2010-2012, TECHIENJOY, All Rights Reserved.      Privacy Policy     Disclaimer & Terms & Conditions