2012-03-20 59 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(); 
...