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.
-
\$\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– Kinjal2013年10月30日 07:36:56 +00:00Commented Oct 30, 2013 at 7:36
-
\$\begingroup\$ of course I handled exception... In my example code, I skipped exception. \$\endgroup\$devpadak– devpadak2013年10月30日 11:53:29 +00:00Commented Oct 30, 2013 at 11:53
1 Answer 1
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
private AModelDAO aDao;
@Transactional
public void something(object) {
// no need to manage transactions or sessions here
aDao.save(object);
}
}