My database worker is implemented above the Hibernate. If something goes wrong, it’s methods should rollback the transaction and throw an SQLException. So my question is: what is the best (i.e. cleanest) way to handle Hibernate exceptions? Currently all my methods looks as ugly as this:
public EntryUserHib addUser(final String username, final String pwdhash) throws SQLException{
try {
final Transaction ta = sess.beginTransaction();
try {
// Using Hibernate here
// "return" statement
} catch(final HibernateException ex) {
try {
ta.rollback();
} catch(final Exception ex1) {}
throw ex;
} finally {
if (!ta.wasRolledBack()) ta.commit();
}
} catch(final HibernateException ex) {
if (ex.getCause() != null) {
if (ex.getCause() instanceof SQLException) throw (SQLException)ex.getCause();
throw new SQLException(ex.getCause());
}
throw new SQLException(ex);
}
}
Let someone else manage it for you, like Spring. It has extensive Hibernate and transaction support that will extract all of that code that you’re worried about.