Sessions and Transactions
All changes of persistent objects should happen inside a transaction. No changes of persistent objects will be saved to the database before the transaction is commited. If an exception occurs, the transaction should be rolled back.
JPA Sessions
Here is a code fragment for JPA:
HibernateHelper persistenceHelper = HibernateHelper.getInstance();
javax.persistence.EntityManager entityManager = persistenceHelper.getEntityManager();
javax.persistence.EntityTransaction tx = entityManager.getTransaction();
tx.begin();
try {
// Modify the persistent objects here.
tx.commit();
} catch(RuntimeException e) {
tx.rollback();
throw e;
} finally {
entityManager.close();
}Hibernate Sessions
Here is a code fragment for Hibernate:
com.objectgen.helper.HibernateHelper helper = com.objectgen.helper.HibernateHelper.getInstance();
org.hibernate.Session session = helper.getSession();
org.hibernate.Transaction tx = session.beginTransaction();
try {
// Modify the persistent objects here.
tx.commit();
} catch (Exception ex) {
tx.rollback();
throw ex;
} finally {
session.close();
}Container Managed Transactions
If the code is running in an EJB container, the container will handle transactions. Please refer to the Hibernate documentation for details.
