1
\$\begingroup\$
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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 30, 2013 at 7:06
\$\endgroup\$
2
  • \$\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\$ Commented Oct 30, 2013 at 7:36
  • \$\begingroup\$ of course I handled exception... In my example code, I skipped exception. \$\endgroup\$ Commented Oct 30, 2013 at 11:53

1 Answer 1

1
\$\begingroup\$

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);
 }
}
answered Oct 30, 2013 at 14:28
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.