Refactoring common method header and footer
- by David Wong
I have the following chunk of header and footer code appearing in alot of methods. Is there a cleaner way of implementing this?
Session sess = factory.openSession();
Transaction tx;
try {
tx = sess.beginTransaction();
//do some work
...
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
sess.close();
}
The class in question is actually an EJB 2.0 SessionBean which looks like:
public class PersonManagerBean implements SessionBean {
public void addPerson(String name) {
// boilerplate
// dostuff
// boilerplate
}
public void deletePerson(Long id) {
// boilerplate
// dostuff
// boilerplate
}
}