Monday, January 09, 2006

Why EntityTransaction?

When managing entities outside a J2EE container, you need to obtain an instance of EntityTransaction to manage transactions. Here is an example:

        EntityManager em = null;
try {
em = Persistence.createEntityManagerFactory("em1")
.createEntityManager();
System.err.println("Created entity manager");
Warehouse w = new Warehouse();
w.setName("LONDON WAREHOUSE");
w.setCity("LONDON");

EntityTransaction t = em.getTransaction();

boolean success = false;
t.begin();
try {
em.persist(w);
success = true;
}
finally {
if (success) {
t.commit();
}
else {
t.rollback();
}
}

} catch (Exception e) {
e.printStackTrace();
}
finally {
if (em != null) {
em.close();
}
}

I would like to understand the rationale for introducing a new abstraction for transaction management when the UserTransaction interface already exists. By introducing a different mechanism for out-of-container applications, it will be harder to write code that is environment agnostic ... unless you write a wrapper to hide the differences.

No comments: