有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate对象状态

我正在测试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 Btag.setName("B")不工作)

然后我在case B中取消对session.update(tag);的注释,现在它正在工作。由于对象未合并到case B事务,它应该给出错误

我们可以说我们正在使用factory.getCurrentSession(),这就是为什么不需要合并它,但是如果用factory.openSession();替换它并在每个案例之后关闭会话,它仍然可以工作(在case B中调用update)。那么在什么意义上我们称一个物体是分离的呢


共 (1) 个答案

  1. # 1 楼答案

    案例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.