Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm just wondering if the following is the best way to write a dao function. Should I get the entity manager before the transaction and close it after the transaction every time? Should I write transactions inside a dao?

public void sendBack(Long requestId,String comments){
    EntityManager em = getEntityManager();
    em.getTransaction().begin();
    String update = "update CsRequestReceivers set activeInd = :activeInd,sendBackComments=:comments where requestId = :requestId and activeInd = :oldActiveInd";
    em.createQuery(update).setParameter("activeInd", 0l)
                          .setParameter("comments", comments)
                          .setParameter("requestId", requestId)
                          .setParameter("oldActiveInd", 1l)
                          .executeUpdate();
    em.getTransaction().commit();
    em.close();
}
share|improve this question
    
I think you refer to this thread of stackoverflow. Link –  Shashank_Itmaster Feb 28 '11 at 8:10

1 Answer 1

up vote 2 down vote accepted

It depends on your app context. If im writting a web app Id create a filter which would getEntityManager(), begin() the transaction, then add it to the request scope, .doFilter() and pass it to the dao in the constructor (at the controller, of course).

When it returns to the filter id commit(), or even rollback() if any exception happens.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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