2016-02-29 73 views
0

我想知道當我在hibernate中使用c3p0連接池時是否應該使用session.close()?或c3p0在一定的時間間隔後自動關閉?我是否需要通過打開會話會話?

SessionFactory factory = HibernateUtil.getSessionFactory(); 
Session session=factory.openSession(); 

因爲在下面的教程中它不會關閉會話。

http://examples.javacodegeeks.com/enterprise-java/hibernate/hibernate-connection-pool-configuration-with-c3p0-example/

什麼是正確的方法是什麼?

編輯:

這將是我的代碼

@SuppressWarnings("unchecked") 
@Override 
public JSONObject getUserDetails(int id) { 
    long lStartTime = new Date().getTime(); 
    JSONObject obj = new JSONObject(); 
    try(Session session=factory.openSession()) { 
     Employee emp=(Employee)session.load(Employee.class,id);  

     if(emp != null) { 
      obj.put("id", emp.getId()); 
      obj.put("name", emp.getName()); 
     }     
     long lEndTime = new Date().getTime(); 
     log.info("[ Personal Details ]Time elapsed For Fetching :"+(lEndTime - lStartTime)); 

    } catch (Exception e) { 
     // TODO: handle exception 
    } 
} 

回答

2

我建議你close你的資源,只要你能,這樣的連接將被返回到池中更快。您也可以使用try-with-resources Statement來確保發生。

SessionFactory factory = HibernateUtil.getSessionFactory(); 
try (Session session = factory.openSession()) { 
    // ... 
} 
+0

謝謝艾略特。但是,我的問題是我應該在代碼中明確寫入「session.close()」嗎? – Syed

+0

如果你不使用'try-with-resources',那麼**是**你應該明確地*在'finally''塊中寫'session,close()'。 –

+0

感謝您的更新。但究竟是什麼使差異? – Syed

0

正如艾略特說,它能夠更好地手動關閉會話不依靠任何東西,或者你可以使用上面,如果你使用的是Java 7或者以上規定的try塊。

0

是的使用try-with-resources是一個更好的選擇。

但這裏有幾個公設一下:

  1. 從試-與資源語句拋出的任何異常都 抑制。
  2. 您可以使用catch,最終像正常 一樣阻止try-catch。
  3. 可以聲明通過分號在try-與資源內部分隔的多個資源,如
try (
     java.util.zip.ZipFile zf = 
      new java.util.zip.ZipFile(zipFileName); 
     java.io.BufferedWriter writer = 
      java.nio.file.Files.newBufferedWriter(outputFilePath, charset) 
    ) 
  • 它的結束後關閉的資源先嚐試阻止,即如果有任何異常來自嘗試阻止或不阻止。之後它執行捕捉,最後阻止。
  • 在try-with-resource語句中聲明的資源必須實現AutoCloseable或Closeable接口。