Reputation: 10812
In my web app I use the session-per-request pattern. I have a connection pool and open sessions in a Filter
using SessionFactory.openSession()
and then Session.close()
.
In the same app, for a complex process, I want to use session-per-conversation. I tried to open a second Session with SessionFactory.openSession()
, but subsequently calling Session.disconnect()
does nothing.
How can I manually connect/disconnect sessions? This is my Hibernate configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost/.....</property>
<property name="hibernate.connection.username">...</property>
<property name="hibernate.connection.password">...</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.test_connection_on_checkout">true</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
</session-factory>
</hibernate-configuration>
The Java code:
longSession = mySessionFactory.openSession();
System.out.println(((SessionImplementor) longSession).isConnected());
longSession.disconnect();
System.out.println(((SessionImplementor) longSession).isConnected());
This outputs true
twice...
Upvotes: 0
Views: 3266
Reputation: 960
I think this is related to this note in Hibernate Documents:
Note that disconnect() called on a session where the connection was retrieved by Hibernate through its configured ConnectionProvider has no effect, provided ConnectionReleaseMode.ON_CLOSE is not in effect
Also note to this in Documentation for session-per-conversation:
Committing a database transaction disconnects a session from the JDBC connection and returns the connection to the pool
This say you need only to commit transactions to return the connection to the pool, except for the last transaction in your conversation:
// foo is an instance loaded earlier by the old session
Transaction t = session.beginTransaction(); // Obtain a new JDBC connection, start transaction
foo.setProperty("bar");
session.flush(); // Only for last transaction in conversation
t.commit(); // Also return JDBC connection
session.close(); // Only for last transaction in conversation
Upvotes: 1