SessionFactory sessionFactory = HBConfig.sessionFactory();
Transaction transaction = null;
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
User user = new User("salib", "ss@ss", "ss", Role.ADMIN);
session.save(user);
User user2 = session.createQuery("from User u where id = 2", User.class).getSingleResult();
transaction.commit();
session.close();
}
catch (Exception ex) {
if (transaction != null) {
transaction.rollback();
}
}
In the above code, session.createQuery
statement throws exception as there is no user with id 2 in the database. then it comes to catch block and executes transaction.rollback()
statement. after that, i checked the db and found the saved user in the user table. how is that happend? the transaction was rollbacked properly int the code. FlashMode was auto and I suppose it flushed before the execution of the query but it was never committed.