具有 Struts2 个操作的 Hibernate 事务上下文

Hibernate Transaction Context with Struts2 Actions

我有一个场景,其中 Struts2 操作从后端获取模型对象并将其放入 OGNL 堆栈,然后使用该数据更新前端视图。

然后我在视图中更改与模型对象对应的值并更新。然后使用 Hibernate 的 getSession().update(model) 方法保存该值。

问题:当模型对象被读入 OGNL 堆栈时,事务上下文关闭并且模型对象被分离。 为什么允许我使用 getSession().update(model) 保存更改? 我认为应该使用getSession().merge(model)

请帮助我理解歧义。

这两种方法都可以将 detached 对象作为参数传递,但如果上下文中存在具有给定标识符的对象,则第一个方法会抛出异常。阅读

Update the persistent instance with the identifier of the given detached instance. If there is a persistent instance with the same identifier, an exception is thrown.

public void update(Object object);

第二种方法不会抛出异常,因为它通过标识符将不存在的对象加载到上下文中,更新它,然后 returns 给调用者。

Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session.

public Object merge(Object object);