2012-03-30 32 views
1

請考慮以下兩個代碼。在HIbernate/SQL中獲取會話和發佈會話的最佳方法

Session session = null; 
query = "update Employee set EMPLOYEE_NAME = 'Jay' where EMPLOYEE_ID = 1"; 

    try { 
     session = getSession(); 
     Query query = session.createSQLQuery(dlquery); 
     query.executeUpdate(); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
    finally { 
     if(session != null) { 
      releaseSession(session); 
     } 
    } 

而且....

Session session = getSession(); 
query = "update Employee set EMPLOYEE_NAME = 'Jay' where EMPLOYEE_ID = 1"; 
    try { 
     Query query = session.createSQLQuery(dlquery); 
     query.executeUpdate(); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
    finally { 
     if(session != null) { 
      releaseSession(session); 
     } 
    } 

兩個中哪個更好用?或者,還有更好的方法?我可能會在這裏做什麼錯?

而且我們應該做最後調用releaseSession(會話)之前空校驗?

回答

2

誠然,最好的辦法就是利用Spring和JPA的/ Hibernate的支持....你永遠不會在你的代碼來處理它。

1

說實話,我說沒有太多區別兩個可言,但你應經常檢查,如果會話爲空,只是讓你不會引起其他的NullReferenceException。

不幸的是,這可能是在Java中執行此操作的最簡單方法,因爲沒有像C#中的「using」語句那樣的事情,它允許您在using塊完成執行後處理對象。

1

我會建議使用一個事務。如果明天你改變你的代碼來添加另一個更新,你就不必擔心任何一致性問題,以免在執行更新時發生某些事情。除此之外,我會建議在查詢中使用參數,而不是硬編碼值。這樣你可以重用查詢。

0

使用下面的語法來獲取和釋放會話。

 session = getSession(); 
     Query query = session.createSQLQuery(dlquery); 
     query.executeUpdate(); 
     session.close(); 
1

如果getSession()拋出Exception出於某種原因,那豈不是在第二個解決問題嗎?