2012-03-20 60 views
4

我測試休眠這裏的情況和代碼:Hibernate的對象狀態

public static void main(String[] args) { 
    SessionFactory factory = HibernateUtil.getSessionFactory(); 
    Tag tag; 

    // (case A)  
    Session session = factory.getCurrentSession(); 
    Transaction tx = session.beginTransaction(); 
    tag = (Tag) session.get(Tag.class, 1); 
    tag.setName("A"); 
    tx.commit(); 
    // session is automatically closed since it is current session and I am committing the transaction 
    // session.close();  

    //here the tag object should be detached 

    //(case B) 
    session = factory.getCurrentSession(); 
    tx = session.beginTransaction(); 
    // tag = (Tag) session.merge(tag); // I am not merging 
    tag.setName("B"); //changing 
    // session.update(tag); 
    tx.commit(); 
    // session.close(); 
} 

它不適合case B更新(tag.setName("B")不工作)。

然後我取消session.update(tag);case B,現在它工作。它應該給錯誤,因爲對象不合併到case B事務。

我們可以說,我們正在使用factory.getCurrentSession()這就是爲什麼沒有需要合併,但如果與factory.openSession();取代它,它仍然是工作每種情況後,關閉會話(與case B調用更新)。那麼在某種意義上,我們稱之爲分離的對象?

回答

3

情況A: 會話未關閉,對象tag處於持久狀態,並且它(標記對象)與當前會話相連。

情況B: 這裏的會話可能與第一筆交易相同,您將更改值爲tag的對象處於持續狀態。 Persistent state represents existence of object in permanent storage. There will be connection between the object in memory and in database through the identifier. Any change in either of these two will be reflected in other (when transaction is committed). Persistent state is dependent on session object. First, session has to be open (unclosed) [這是真的,你的情況] , and second, the object has to be connected to the session. If either of these two is not true, then the object moves into either transient state or detached stage.

對象處於分離狀態在以下情況: Detached state arises when a persistent state object is not connected to a session object. No connection may be because the session itself is closed or the object is moved out of session.

0

關於對象的狀態:

休眠區分對象的三個狀態:持續,瞬態和分離。

  1. 對象的瞬態狀態 - 是從未與Hiberbate會話相關聯的對象。通常這是持久類的新實例,它在數據庫中沒有表示,並且沒有標識符值。

  2. 對象的持久狀態 - 是當前與Hiberbate會話相關聯並且具有數據庫中的表示並具有標識符值的對象。

  3. 對象的分離狀態 - 是從持久狀態移出並在數據庫中有表示的對象。當會話關閉時,對象的狀態從持續狀態變爲已去除狀態。

實施例:

... 
// Tag in a transient state 
Tag tag = new Tag(); 
tag.setName("A"); 

// Tag in a persistent state 
Long id = (Long) session.save(tag); 

// Tag in a detached state 
session.close(); 
...