0

I'm trying to write DAOs for my database models using the transaction pattern like such,

    Session session = null;
    Transaction tx = null;

    try{
        session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();
        tx.setTimeout(5);

        //doSomething(session);

        tx.commit();


    }catch(RuntimeException e){
        try{
            tx.rollback();
        }catch(RuntimeException rbe){
            log.error("Couldn’t roll back transaction", rbe);
        }
        throw e;
    }finally{
        if(session!=null){
            session.close();
        }
    }

What's a good approach to encapsulate this pattern in a method with

        //doSomething(session);

as an argument to be performed as part of the transaction? Sometimes I run a query, sometimes I operate on session.saveOrUpdate, etc. I have many DAOs to write and this pattern of code duplication is bothering me.

EDIT

Is there a direct mapping between session operations and HQL (saveOrUpdate, delete, etc) so all I need to pass into this method is just a query?

Thanks for the insights.

4

1 回答 1

1

像这样的东西可能就是你所追求的

public void doSomething(MyQuery myQuery) {
    ...
    Transaction tx = null;
    try {
        ...
        myQuery.execute(tx);
        ...
    } catch (...) {
    } finally {
    }
}

public class MyQuery {
    public void execute(Transaction tx) {
        // run queries on transaction
    }
}

为要执行的每个查询或一组查询创建一个新MyQuery实例或一个新子类MyQuery

于 2013-06-08T23:26:30.473 回答