Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm new to Hibernate so I need some advice/direction on doing Transactions.

I have a DAO like

public class MyDao extends HibernateDaoSupport implements IMyDao {

 @Override
 public Foo getFoo(int id) {

  return (Foo)getHibernateTemplate().load(Foo.class, id);

 }
}

With this setup (using HibernateDaoSupport), will Hibernate/Spring handle transactions for me? Some of the examples I see say yes, others show using

Transaction tx = getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction();

to get a Transaction in every DAO method.

Right now I'm assuming my minimal DAO is correct but I want to do a "larger" transaction that includes a couple of Hibernate calls in one method. Would I use the manual Transaction method there? Do I have to use it everywhere? Thanks.

share|improve this question
Belongs on stackoverflow? – Michael K Jan 28 '11 at 14:04
1  
Yup, the question here is clearly not "does it make my ass look fat", but "does it work" (see this meta answer : meta.codereview.stackexchange.com/questions/138/… ) – Riduidel Jan 28 '11 at 15:04
I was torn on whether this belongs on SO or not since what I have might be right, I just want to know if it's the right way of doing it or not. I'm fine with moving it though. – MattGrommes Jan 28 '11 at 19:09

closed as off topic by Robert Cartaino Feb 3 '11 at 17:01

Questions on Code Review Stack Exchange are expected to relate to code review request within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

2 Answers

In general, you should never handle transactions in dao code, as you never know where the transaction boundary is. You should let whoever wants to control the transactions control them.

Code that starts and commits a transaction in every dao method is likely to be problematic.

Btw: not very keen at all on 'dao' but as you use it, so will i.

share|improve this answer

I would personally introduce spring and their hibernate support into your application then you can use there hibernate transaction manager and define transactions in the xml file and then forget about them in the actual code

share|improve this answer
I actually have Spring set up and I thought using the HibernateDaoSupport would handle transactions automatically. I'll look into any needed xml changes, thanks. – MattGrommes Jan 31 '11 at 18:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.