【问题标题】:What will be the outcome if an entity object is accessed after transaction.commit() in Hibernate?如果在 Hibernate 中的 transaction.commit() 之后访问实体对象会是什么结果?
【发布时间】:2017-07-06 09:09:17
【问题描述】:

我是休眠新手。我想了解事务提交后的行为。考虑下面的代码-

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();
 }
}

【问题讨论】:

    标签: java hibernate transactions entity commit


    【解决方案1】:

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

    可以通过调用 delete() 将持久实例变为瞬态

    来自指南:

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

    在这里查看更多信息https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html

    【讨论】:

    • 感谢您的指点。这是否意味着提交后访问的瞬态对象将表现为普通对象并且 getName() 将返回 null 值?
    • 如果 getName() 在 commit() 之前不为 null,那么在 commit() 之后也不为 null。
    猜你喜欢
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 2019-09-10
    • 2020-11-15
    相关资源
    最近更新 更多