Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting variable from try-with-resources in catch block

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();
        }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
        }
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading