Оur project has upgraded the version hibernate to 5.2.3.Final
The Session interface has started to implement the AutoCloseable interface.
we have a strange project, and hibernate is used primitively:
Session session = mySqlSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
//code
transaction.commit();
} catch (Exception ex) {
if (transaction != null) transaction.rollback();
throw ex;
} finally {
session.close();
}
is it possible to open a session in the try-with-resources construct and not use the catch block to roll back the transaction if an error occurs?
try (Session session = mySqlSessionFactory.getSessionFactory().openSession()) {
Transaction transaction = session.beginTransaction();
//code
transaction.commit();
}
or even so, along with @Cleanup from lombook?
@Cleanup Session session = mySqlSessionFactory.getSessionFactory().openSession());
Transaction transaction = session.beginTransaction();
//code
transaction.commit();
If I use a session in try-with-resources and a catch block with a transaction rollback, then if there is an error in the code, the session is closed first, and then the transaction is rolled back, which also causes the error to fall
try (Session session = mySqlSessionFactory.getSessionFactory().openSession()) {
Transaction transaction = session.beginTransaction();
//code
transaction.commit();
} catch (Exception ex) {
if (transaction != null) transaction.rollback();//Exception: Session is closed
throw ex;
}