According to this answer https://stackoverflow.com/a/3588173/22172432, if we don't commit or rollback a transaction, it will be timed out and rollback. So why we should rollback a transaction in catch block if it will be rolled back anyway? I've read in a tutorial that "In hibernate, it is better to rollback the transaction if any exception occurs, so that resources can be free." , but what does "resources" mean? Does hibernate keep a physical transaction in database open? AFAIK no, because hibernate has a local cache (persistence context), and first it writes any changes to its context, and it is just a logical notion of a transaction as related to a persistence context.
Example code:
SessionFactory factory = new Configuration()
.configure("persistence.xml")
.addAnnotatedClass(Employee.class)
.buildSessionFactory();
Session session = factory.getCurrentSession();
var transaction = session.beginTransaction();
try {
Employee person1 = session.get(Employee.class, 1L);
person1.setSalary(100000d);
if (true) {
throw new RuntimeException("error!");
}
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
if (transaction.isActive())
transaction.rollback();
}
If you don't rollback or commit the transaction, Hibernate will hold the connection until the transaction is timed out, so every request will take one new connection from the connection pool and it(connection pool) can reach it's maximum size. Therefore you should rollback or commit the transaction when you finish your work or get an exception.