I just read the Wiki entry on "Sessions and transactions"
http://www.hibernate.org/42.html
In section "Transaction demarcation with JTA" the second code example raises the question whether it is really correct:
Code:
// code from the Hibernate wiki
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
Session session = factory.openSession();
try {
tx.begin();
// Do some work
session.load(...);
session.persist(...);
session.flush();
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
finally {
session.close();
}
In this example the Hibernate session is managed by the programmer himself. The pattern is comparable to the use of an application-managed entity manager with JPA. With JPA an application-managed entity manager created inside a transaction will automatically synchronize its persistence context with the transaction. By contrast, an application-managed entity manager created outside of a transaction needs to explicitly join the JTA transaction by calling joinTransaction() on the EntityManager interface.
This (or something similar) is not done in above Hibernate example however.
My question therefore: Is above Hibernate example taken from the Wiki really correct? How does the Hibernate session become aware of the transaction which began
after the session had been created already?
A clarification would be highly appreciated.
Compare how it would look like with JPA:
Code:
// comparable pattern with JPA
@Stateful
public class JPAExampleBean {
@PersistenceUnit(unitName="xxx")
EntityManagerFactory emf;
EntityManager em;
public void init() {
// application-managed EntityManager created outside of a transaction
em = emf.createEntityManager();
...
}
public void persistSomeEntity(Entity e) {
// as the EntityManager was created outside of a transaction,
// we need to call em.joinTransaction(); in order to synchronize
// the persistence context with the database when the transaction
// commits.
em.joinTransaction();
em.persist(e);
...
}
... more methods of the StateFul Session Bean...
@Remove
public void finish () {
...
}
}