I am having a hard time not to repeat myself in a Java program I am working on at the moment.
Say, I need to declare a lot of methods that basically are structured in the following way:
public SomeEntity doSomething (String someAttribute, String anotherAttribute) {
EntityManager em = this.createEntityManager();
EntityTransaction tx = null;
try {
/*
* ... independent logic ...
*/
tx = em.getTransaction();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw e;
} finally {
em.close();
}
return something;
}
The method body of all methods needs to contain theses elements for resource management.
The "independent logic" itself will be rather complex too, so putting the try/catch statement in a separate method won't really work.
I want to avoid to repeat this code. What are the best practices to apply in these situations?