2016-04-22 131 views
0

在我的Web應用程序中,我使用會話每請求模式。我有一個連接池,並使用SessionFactory.openSession()然後Session.close()Filter中打開會話。如何斷開休眠會話

在同一個應用程序中,對於一個複雜的過程,我想使用會話每個對話。我試圖用SessionFactory.openSession()開啓第二場會議,但隨後致電Session.disconnect()什麼都不做。

如何手動連接/斷開會話?這是我的Hibernate配置文件:

<?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> 

的Java代碼:

longSession = mySessionFactory.openSession(); 
System.out.println(((SessionImplementor) longSession).isConnected()); 
longSession.disconnect(); 
System.out.println(((SessionImplementor) longSession).isConnected()); 

此輸出true兩次......

回答

1

我認爲這是Hibernate Documents與此相關的注意事項:

請注意,在會話中調用disconnect()方法時,co nnection是 由Hibernate通過其配置ConnectionProvider來檢索具有 沒有效果,提供ConnectionReleaseMode.ON_CLOSE未生效

還要注意這個在Documentation for session-per-conversation:

提交一個數據庫事務從斷開的會話JDBC 連接並返回連接池

這就是說你只需要提交trans操作返回到池的連接,除了在與你交談的最後一個交易:

// 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 
+0

我知道,但我到處看的session-per-交談一下,但不知道實際調用使用它什麼。我應該如何配置Hibernate才能斷開會話連接? – Oliv

+0

我應該如何打開會話才能斷開連接? – Oliv

+0

@Oliv我無法理解你爲什麼不想使用'session.close()'? –