Create an interface:
public interface EntityManagerAction {
public void execute(EntityManager em);
}
And a utility class:
public class EntityUtil {
public static void executeWithEntityManager(EntityManagerAction action) {
EntityManager em = someHowCreateEntityManager();
EntityTransaction tx = null;
try {
action.execute(em);
tx = em.getTransaction();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw e;
} finally {
em.close();
}
}
}
Now you can re-use the boiler-plate in the EntityUtil class, and your code becomes:
public SomeEntity doSomething (String someAttribute, String anotherAttribute) {
Something something;
EntityUtil.executeWithEntityManager(new EntityManagerAction() {
public void execute(EntityManager em ) {
/*
* ... independent logic ...
*/
//use the passed in 'em' here.
}
});
return something;
}
See also What is the “Execute Around” idiom?