我測試休眠這裏的情況和代碼: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
調用更新)。那麼在某種意義上,我們稱之爲分離的對象?