public void something()
    Session session = HibernateUtil.newSession();
    AModelDAO amd = new AModelDAO(session);
    BModelDAO bmd = new BModelDAO(session);

    Transaction tx = session.beginTransaction();

I would like to know if my coding here is good enough or if there is a better method to produce the same result.

  • \$\begingroup\$ I do not know hibernate. This is a general guideline that you should handle exception here and also think of the case where the transaction fails and how you revert back the state. \$\endgroup\$
    – Kinjal
    Oct 30 '13 at 7:36
  • \$\begingroup\$ of course I handled exception... In my example code, I skipped exception. \$\endgroup\$
    – devpadak
    Oct 30 '13 at 11:53

Instead of working with Hibernate sessions, I encourage you to use the JPA API. I think this is the most common way to work with Hibernate now. (http://www.theserverside.com/news/2240186700/The-JPA-20-EntityManager-vs-the-Hibernate-Session-Which-one-to-use)

For the transaction aspects and the initialization of your DAOs, I also think that a solution like Spring (http://projects.spring.io/spring-framework/) would help to simplify the code of your application.

Your code would look more like the following (with annotations stuff):

public class MyService {
  private AModelDAO aDao;

  public void something(object) {
    // no need to manage transactions or sessions here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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