gpt4 book ai didi

java - 如果在 Hibernate 中访问 transaction.commit() 之后访问实体对象,结果会怎样?

转载 作者:行者123 更新时间:2023-11-30 10:33:17 25 4
gpt4 key购买 nike

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

最佳答案

它变成了“ transient ”。来自Session类文档

Persistent instances may be made transient by calling delete()

来自指南:

Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).

查看此处了解更多信息 https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html

关于java - 如果在 Hibernate 中访问 transaction.commit() 之后访问实体对象,结果会怎样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42287794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com