I'm using a Data Access Object (DAO) pattern in Java and I have the same piece of code repeated all over my files. The thing is somethimng like this:
public User getById(int id) throws BDException {
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.getTransaction();
try {
tx.begin();
Query query = session.createQuery("SELECT u FROM User u WHERE u.id=:id");
query.setString("id", id);
User user = (User) query.uniqueResult();
tx.commit();
return user;
}
catch(javax.validation.ConstraintViolationException | org.hibernate.exception.ConstraintViolationException cve) {
try {
if(tx.getStatus() == TransactionStatus.ACTIVE) {
tx.rollback();
}
}
catch(Exception exc) {
LOGGER.error("Error rollback in method='" + getMethodName() + "'");
}
throw new BDException(cve);
}
catch(RuntimeException ex) {
try {
if(tx.getStatus() == TransactionStatus.ACTIVE) {
tx.rollback();
}
}
catch(Exception exc) {
LOGGER.error("Error rollback in method='" + getMethodName() + "'");
}
throw ex;
}
catch(Exception ex) {
try {
if(tx.getStatus() == TransactionStatus.ACTIVE) {
tx.rollback();
}
}
catch(Exception exc) {
LOGGER.error("Error rollback in method='" + getMethodName() + "'");
}
throw new RuntimeException(ex);
}
}
Well, I want you to look at the catch's part. I have it repeated in every method I have. If it was simple code, I could create a method, put all that code inside and call the method instead of repeat the code. The problem is that it is not normal code, they are exceptions.
So, is there any solution to reuse code and not to repeat (copy-pasting) the code in every method?
Thanks!