1

I'm developing a JavaFX Hibernate desktop application. I configured my application so that I use the same session from the application runs till it close. This is how I did it:

public static Session getCurrentSession() {
    if (sessionFactory != null) {
        Session session = sessionFactory.getCurrentSession();
        if (session != null) {
            return sessionFactory.getCurrentSession();
        } else {
            session = sessionFactory.openSession();
            session.beginTransaction();
            return session;
        }
    }
    return null;
}

And when the User close the App, I run a second method that closes the session and the SessionFactory.

public static void closeConnections() {
    if (sessionFactory != null) {
        if (sessionFactory.getCurrentSession().isOpen()) {
            sessionFactory.getCurrentSession().close();
        }
        sessionFactory.close();
    }
}

I'm newB on Hibernate so be kind with me PEACE

BilalDja
  • 1,072
  • 1
  • 9
  • 17

2 Answers2

5

Hibernate session should be thought of as a "single-unit-of-work". One or more transactions can live in a session. The best practice is in most cases session-per-request.Open a session in the beginning of handling a request, and close it in the end.

Hibernate's 1st level cache is mantained in the "Session" so that if you keep it around in the user session it will be hitting "cached" objects.

Hibernate has 2nd level cache that you have to configure (if you want) to take advantage of. The 2nd level basically supports the following: queries, objects with load and get, and collections/associations and provides cached objects across Sessions, SessionFactories, and Clusters.

You are not using one session per application, you are using the "current session" concept, which opens a session and stores it in a context.If you don't close your session it will stay there.

Moni
  • 433
  • 3
  • 9
  • In a JavaFX desktop application, there's no real concept of a request, other than as defined by the code itself. (Unlike a web application, where you write code specifically to service a request.) So, in reference to your penultimate sentence, what is the context in which the session is stored, in a desktop application? – James_D Oct 02 '14 at 00:34
2

OK, for your basic question:

Is it a good practice to use the same Hibernate Session over and over?

Answer is no,the session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.

What it is usually done in hibernate is:

You open a session (which is basically a database connection), do transactions, and then close your connection (close your session). In other words, you can check some other post's analogy :

What is the difference between a session and a transaction in JPA 2.0?

Hope it helps

Community
  • 1
  • 1
Cesar Villasana
  • 681
  • 3
  • 6