# Coherent usage of Hibernate's session and DAO

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

Transaction tx = session.beginTransaction();
amd.savesomething(object);
bmd.savesomething(object2);
tx.commit();
session.close();
}


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

• 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. – Kinjal Oct 30 '13 at 7:36
• of course I handled exception... In my example code, I skipped exception. – 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 {
@Resource