1) If you have JTA available, I would definitely use that. Set the hibernate.current_session_context_class property to "jta" and whenever you start a JTA transaction, the getCurrentSession() call will return the Hibernate session bound to that JTA transaction automatically (session-per-request semantics). From the javadocs of org.hibernate.context.JTASessionContext:
Javadocs wrote:
If a session is not already associated with the current JTA transaction at the time currentSession() is called, a new session will be opened and it will be associated with that JTA transaction.
Note that the sessions returned from this method are automatically configured with both the auto-flush and auto-close attributes set to true, meaning that the Session will be automatically flushed and closed as part of the lifecycle for the JTA transaction to which it is associated. Additionally, it will also be configured to aggressively release JDBC connections after each statement is executed.
2) Service layer = business layer, it's just semantic differences. Definitely start and commit your transactions there to encapsulate your business logic. For example:
Code:
public void saveMyData(MyData myData) {
UserTransaction tx = HibernateUtils.beginTransaction();
if (businessRequirementsMet) {
HibernateUtil.getSessionFactory().getCurrentSession().persist(myData);
} else {
// Handle business rules/validation errors
}
try {
tx.commit();
} catch (Exception e) {
tx.rollback();
// Do commit error handling here
}
}
If you want, you can still use the thread bound transaction demarcation (the ThreadLocal in your current HibernateUtils) to begin, commit and rollback transactions as needed, providing further abstraction, which would make the code look like this:
Code:
public void saveMyData(MyData myData) {
HibernateUtils.beginTransaction();
if (businessRequirementsMet) {
HibernateUtil.getSessionFactory().getCurrentSession().persist(myData);
} else {
// Handle business rules/validation errors
}
try {
HibernateUtils.commitTransaction();
} catch (Exception e) {
HibernateUtils.rollbackTransaction();
// Do commit error handling here
}
}
Again, check out
http://www.hibernate.org/400.html and look at the HibernateUtils class there (auction.persistence.HibnerateUtil). It's the best start, notice the lack of ThreadLocal variables to hold a Session.