Luke
Luke

Reputation: 1053

How to Encapsulate Transaction Pattern in Java

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.

Upvotes: 0

Views: 541

Answers (1)

Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18148

Something like this might be what you're after

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
    }
}

Either create a new MyQuery instance or a new MyQuery subclass for each query or set of queries you want to execute

Upvotes: 1

Related Questions