Java Hibernate Sessions Don't Get Killed Correctly

I am using Hibernate for my Java application.

When hibernate open a connection, JDBC thin client open a session like this:

enter image description here

After my work with the Oracle DB is done, I close the opened session. Session get closed and inactive rather then completely geting killed. I also tried using session.flush() command before closing the session but again it didn’t work.

What should I do to completely kill and delete these sessions?

An example of database connection and closing it in the end:

Session session = null;
Transaction transaction = null;

try
{
    session = DatabaseConnection.GetDatabaseSession();
    transaction = session.getTransaction();
    transaction.begin();

    /*
        Something something
    */

    transaction.commit();
}
catch (Exception exp)
{
    exp.printStackTrace();
}
finally
{
    if (session != null && session.isOpen())
    {
        session.close();
        session.flush();
    }
}

And my GetDatabaseSession() method:

public static Session GetDatabaseSession() throws FileNotFoundException, NullModelException
{
    String connectionUrl = "jdbc:oracle:thin:@" + IPADDRESS + ":" + DBPORT + ":" + DATABASE;

    Properties properties = new Properties();
    properties.put("hibernate.dialect", "org.hibernate.dialect.OracleDialect");
    properties.put("hibernate.connection.driver_class", "oracle.jdbc.driver.OracleDriver");
    properties.put("hibernate.connection.url", connectionUrl);
    properties.put("hibernate.connection.username", USERNAME);
    properties.put("hibernate.connection.password", PASSWORD);
    properties.put("hibernate.default_schema", SCHEME);
    properties.put("hbm2ddl.auto", "update");
    properties.put("hibernate.query.substitutions", "true 0, false 1");

    return new Configuration()
            .addProperties(properties)
            .addAnnotatedClass(SOMECLASS.class)
            .buildSessionFactory(
                    new StandardServiceRegistryBuilder()
                            .applySettings(properties)
                            .build()).openSession();
}

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

It looks like I had to close SessionFactory entity to completely kill the session opened by my Hibernate. The code would be like that:

public static SessionFactory sessionFactory = null;

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

One indirect solution for my problem is creating Signleton Hibernate SessionFactory as described here: Singleton Hibernate SessionFactory Example