开发者

implementing a dao class properly to manage transactions

I am working on a java web application that calls database backend through hibernate.I use servlets,jsp and tomcat for test/deployment.Most books on java-ee suggested using Dao classes for database calls.As per examples given in books(Hibernate Recipes by Gary Mak),I created a generic base class and a specific subclass as below.

class BaseDao{
   private Class persistentClass;
   public BaseDao(Class persistentClass) {
        super();
        this.persistentClass = persistentClass;
    }
   public Object findById(Long id) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();
        Object object = null;
        try {
            object = (Object) session.get(persistentClass, id);
            return object;
        }
        finally {
            session.close();
        }
    }

    @Override
    public void saveOrUpdate(Object obj) {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        Session session = factory.openSession();
        Transaction tx = null;
        try {
        tx = session.beginTransaction();
        session.saveOrUpdate(obj);          
        tx.commit();
        }catch(HibernateException e){
            if (tx != null) {
                       tx.rollback();   

             }
             throw e;
        }finally {
            session.close();
        }

    }
}

    class SaleOrderDao extends BaseDao{
        public SaleOrderDao() {
            super(SaleOrder.class);
        }
        @Override
       public SaleOrder findSaleOrderById(Long saleOrderId){            
                SaleOrder so =  (SaleOrder)findById(saleOrderId);
                return  so;

        }
        @Overrid开发者_StackOverflowe
        public void saveOrUpdateSaleOrder(SaleOrder so){

                    saveOrUpdate( so);

            }

    }

While going through the posts in this forum ,I came across Ryan Stewart's advice that beginning and ending transactions in a dao method is not recommended..Sadly, my project does not use any web framework that supports transaction management..and I am limited to using jsp,servlets and a servlet container..

Is there some way I can rewrite my dao implementations sothat transactions can be managed properly..I couldn't find anything in this regard from those books I read..

Hope somebody helps me with suggestions

sincerely,

Jim


Normally transactions should not be handled in the DAO. They should be handled by the service layer. One service method may include multiple DAO calls that are all in the same transaction.

Spring (as well as other DI frameworks) allows you to do that by simply annotating your service methods with @Transactional. Without spring you can still do that manually in the service layer

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜