I have the following code for saving a new record (of users) to my MySQL 5.0.22 database:
Code:
User user = getuser();
Session session = null;
Transaction transaction = null;
String strUserId = null;
try {
session = HibernateSessionFactory.getSessionFactory().openSession();
transaction = session.beginTransaction();
strUserId = session.save(user).toString();
// logging ; if an exception happens here, a row in db is still created :(
user.setId(Integer.parseInt(strUserId));
handleLogs.setUsersLog(user, createdById);
// Commit when logging is complete
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
try {
transaction.rollback();
} catch (HibernateException he) {
// log
}
}
throw new NeSystemException(e);
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException he) {
// log
}
}
}
The problem is that if an exception occurs in the logging part, a new row is saved to the database even though transaction.commit() is never executed. I though the new row weren't supposed to be written to the database before after the commit? What's wrong with my code?