如果在Hibernate中的transaction.commit()之后访问实体对象会有什么结果?

时间:2017-02-17 01:26:01

标签: java hibernate transactions entity commit

我是hibernate的新手。我想在事务提交后理解行为。请考虑以下代码 -

Employee类是其对象将在数据库中插入/删除的类。

public static void main(String[] args) {

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.getCurrentSession();

     long id = 2;

 try {
    session.beginTransaction();
    Employee employee = (Employee) session.get(Employee.class, id);
    session.delete(employee);
    session.getTransaction().commit();
    employee.getName(); /*What will happen at this line*/
  }
  catch (HibernateException e) {
    e.printStackTrace();
        session.getTransaction().rollback();
 }
}

1 个答案:

答案 0 :(得分:1)

变成“瞬态”。来自Session类文档

  

通过调用delete()

可以使持久化实例变为瞬态

从指南中:

  

瞬态 - 如果一个对象刚刚使用new运算符进行实例化,并且它与Hibernate会话无关,则该对象是瞬态的。它在数据库中没有持久表示,并且没有分配标识符值。如果应用程序不再持有引用,则垃圾收集器将销毁瞬态实例。使用Hibernate Session使对象持久化(让Hibernate处理需要为此转换执行的SQL语句)。

请点击此处了解详情https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html