Home > Net >  Getting variable from try-with-resources in catch block
Getting variable from try-with-resources in catch block

Time:08-26

here i have try-with-resources to close session after it executes, but also i use session variable in catch block to rollback. The problem is i cant access to session variable that declared in try block from catch block, so the only way i see is to assign session from try block to session, which is class field. Is any way to access session variable from try block in catch block? To get rid of extra lines from this code?

private Session session = null;

public void cleanUsersTable() {
        try (Session session = sessionFactory.openSession()) {
            this.session = session;
            session.beginTransaction();
            session.createQuery("DELETE FROM User")
                    .executeUpdate();
            session.getTransaction().commit();
        } catch (Throwable e) {
            session.getTransaction().rollback();
        }
    }

CodePudding user response:

In Java 9 you can define the session outside of try block and use the reference inside try() like this:

public void cleanUsersTable() {
    Session session = sessionFactory.openSession();
        try (session) {
            this.session = session;
            session.beginTransaction();
            session.createQuery("DELETE FROM User")
                    .executeUpdate();
            session.getTransaction().commit();
        } catch (Throwable e) {
            session.getTransaction().rollback();
        }
   }

As highlighted in comments, we can face an exception while opening the session. A solution would be nested try:

public void cleanUsersTable() {
    try (Session session = sessionFactory.openSession();) {
        try{
            session.beginTransaction();
            session.createQuery("DELETE FROM User")
                    .executeUpdate();
            session.getTransaction().commit();
        } catch (Throwable e) {
            session.getTransaction().rollback();
        }
   }
}
  • Related