Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connection and session closing

I have the following code in the Try bloc :

// Session variable
Session session = null;
// Connection variable
Connection conn = null;

try {
...
// Get hibernate session
session = getHibernateTemplate().getSessionFactory().openSession();
// Get connection frojm session
conn = session.connection();
...
}catch{
...
}

And in the finally bloc i want to bloc all the related object of the connection with the database.

the closing of session makes us to close the connection ? or we have to have to close the connection before ? Solution 1 :

finally{
try{if (conn!=null) conn.close();}ctach{}
try{if (session!=null) session.close();}catch{}
}

Solution 2 :

finally{
try{if (session!=null) session.close();}catch{}
}

In case of one of the two solutions before, can you explain the relationship between session and connection specially through pool way.

like image 277
kaissun Avatar asked Apr 08 '26 08:04

kaissun


2 Answers

Second approach is enough. If you haven't set hibernate.connection.release_mode, then default (auto) is used. According documentation:

By default, a JDBC connection is held until the session is explicitly closed or disconnected.

In case of pool, closing connection means that connection is returned to pool.

like image 57
Mikko Maunu Avatar answered Apr 10 '26 00:04

Mikko Maunu


First, I like to know why you want to close connection in the code mentioned?

When you close a session hibernate makes sure that it does not hold any reference to the connection. In Hibernate 3.6.8, the call is delegated to the ConnectionManager. Check closeConnection() method. In Hibernate 4 when you call session.connection() what you get is a proxy and in hibernate 3, you are most likely get wrapper over connection, if connection pool is configured.

So your option is to debug session.connection() and session.close(), and decide whether you want to close the coneection or not.With the kind of information you provided, any answer here will be pure assumption.

like image 25
Adisesha Avatar answered Apr 10 '26 00:04

Adisesha