Thread:
 Transaction Management in DAOs 
 prashantbasawa   30 Oct 2006, 06:25 
 Re: Transaction Management in DAOs 
 prashantbasawa   30 Oct 2006, 07:28 
 Re: Transaction Management in DAOs 
 bora.erbas   03 Nov 2006, 08:29 
 Re: Transaction Management in DAOs 
 prashantbasawa   13 Nov 2006, 02:12 
 Re: Transaction Management in DAOs 
 christian   14 Nov 2006, 05:19 

Comment
Prev. thread 
 Next thread
 
Prev. posting 
 Next posting
From: prashantbasawa (30 Oct 2006, 06:25) Replies: 4, Views: 24418
Subject: Transaction Management in DAOs
Using transaction management outside the DAO is not a good idea. It
should be done inside the DAO itself. We can use a Strategy Pattern to
plug-in the transactional behaviour into the DAOs.

Declare a interface as 

public interface TransactionStrategy {
   public void beginTransaction();
   public void commit();
}

Have an implementor like,

public class DefaultTransactionStrategy {
   public void beginTransaction(){
      HibernateUtil.getSessionFactory().getCurrentSession()
                                    .beginTransaction();
   }

   public void commit(){
      HibernateUtil.getSessionFactory().getCurrentSession()
                                    .commit();
   }
}

Now in the DAOs, you can have a instance variable declared for the
transaction strategy. Like

public class xyzDAO{
   private TransactionStrategy transaction = null;
   
   public xyzDAO(){
      transaction = new DefaultTransactionStrategy();
   }

   public void insert(Object obj){
      transaction.beginTransaction();
      
      // Do some work
      session.load(...);
      session.persist(...);

      transaction.commit();
   }

   public void setTransactionStrategy(TransactionStrategy strategy){
      transaction = strategy;
   }
}

Thus we can move the transaction management code to a strategy class
which will be used inside the DAOs.

In future, if you want to switch to a JTA Transaction, then you can
create a new transaction strategy for the same. 

Also these strategies can be set to DAOs in
HibernateDaoFactory.instantiateDAO(Class clazz), where we have set the
session. Also, we can take the strategy info from a property file as
well. So based on a property in the property file, you can create a
strategy and set it to the DAOs.

Note: Strategy class can also accept the session through its constructor
if you define one which accepts it.
Prev. thread 
 Next thread
 
Prev. posting 
 Next posting
© Copyright 2006, Red Hat Middleware, LLC. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc. [Privacy Policy]