java - 为什么我需要在使用 Hibernate 查找后显式保存?

标签 java hibernate

为什么我需要“session.save(user);”这一行在下面的代码片段中?我想,通过查找调用,用户已经附加到 session 中,并且将跟踪和提交更改。你介意为我解释细节吗?或者我是否需要特殊配置或其他我可能听说过此“功能”的情况?

session = createSession();
ta = session.beginTransaction();
assertEquals(1, session.createCriteria(MyUser.class).list().size());
// find one user
MyUser user = session.createCriteria(MyUser.class).uniqueResult();
user.setName("Rocker!");
// ### HERE ###
// WHY this 'save' is necessary!!??
session.save(user);
ta.commit();

ta = session.beginTransaction();
assertEquals(1, session.createCriteria(MyUser.class).list().size());
MyUser user = session.createCriteria(MyUser.class).uniqueResult();
assertEquals("Rocker!", user.getName());
ta.commit();

更新 1

同样的问题适用于

  1. session.save(用户);
  2. user.setName("摇杆!");
  3. ta.commit();

更新 2

问题的解决方法是:我使用的是guice/warp persist。在某些情况下,我通过@Transactional 错误地将代码块绑定(bind)到事务:因此事务提交得太早打开,因此单独的更改未包含在提交中。多谢你们!因此,如果您使用的是 spring 或 guice,请始终确保您了解自己的事务范围...

最佳答案

你是正确的,hibernate 应该自动检测持久对象状态的变化:

Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.

我假设条件结果不会以持久状态返回(但我似乎无法在文档中找到这方面的证据)

尝试使用 HQL 查询,文档对此很清楚:

Entity instances retrieved by a query are in a persistent state

还要确保 session 的刷新模式设置为AUTOCOMMIT

关于java - 为什么我需要在使用 Hibernate 查找后显式保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3245482/

相关文章:

java - 如何从PDF文件中提取页码

hibernate - 使用 hibernate 进行缓存

java - hibernate : Foreign key constraint violation problem

java - 让 JTextField 自动调整大小

java - 将对象发送到 Servlet 会引发我无法解决的错误

hibernate - 将参数数组设置为 hibernate 查询语言

java - 如何使受管实体具有上下文感知能力?

hibernate - 一对多映射到父类(super class)的属性

java - 如何从 Firebase 获取所有 Childs 的 Java 对象的 ArrayList

java - 创建太空侵略者类型的游戏,无法阻止射击船离开边界框