问题描述
我有一个简单的编辑器UI用于在数据库表上执行CRUD。
在Hibernate 5.1下,这个过程是:
- 创建一个会话。读入数据对象。关闭会话,分离对象。
- 使用分离的对象填充UI小部件。
- 允许用户添加/编辑/删除UI,修改分离的对象。
- 在用户保存操作中:创建一个新会话。使用saveOrUpdate()持久保存新的/更新的对象。关闭会话。
- 根据需要重复操作。
$ b Hibernate 5.2强烈建议从Hibernate-本地API到JPA API。 JPA不允许您重新附加分离的对象。
有两种解决方法:
- 使用unwrap从JPA EntityManager获取Hibernate会话,并使用它来调用saveOrUpdate。我不喜欢这个选项,因为它依赖于不属于JPA一部分的功能。
- 使用JPA合并,它会更新持久化对象,尽管我必须确保我不要破坏任何关联。这给了我同一个对象的两个副本,一个持久化,一个分离...这是混乱的。
- 执行手动合并操作,将修改的字段从分离的对象复制到持久对象。这是额外的工作。
- 在整个过程中保持单个EntityManager实例的活动。不幸的是,其他线程可以在此会话仍处于打开状态时执行CRUD操作,从而使持久性上下文与数据库表不同步。所以我也不喜欢这种方法。
有没有什么好的方法可以做到这一点,或者这些是唯一的选择可用吗?
JPA规范定义了 merge()
操作。该操作似乎对实现所描述的用例很有用。
请参考规范:
I have a simple editor UI for performing CRUD on a database table.Under Hibernate 5.1, the process was:
- Create a session. Read in data objects. Close session, detaching the objects.
- With the detached objects, populate the UI widgets.
- Allow user to add/edit/remove entries in the UI, modifying the detached objects.
- On a user "save" action: Create a new session. Persist new/updated objects with saveOrUpdate(). Close session.
- Repeat as required.
Hibernate 5.2 strongly recommends moving from the Hibernate-native API to the JPA API. JPA does not allow you to reattach detached objects.
There are a couple of workarounds:
- Use unwrap to get the Hibernate session from the JPA EntityManager, and use it to call saveOrUpdate. I don't like this option because it relies on functionality that is not part of the JPA.
- Use JPA merge, which will update the persisted object, although I've got to ensure I don't break any associations. This gives me 2 copies of the same object, one persisted, one detached... which is messy.
- Perform a manual merge operation, copying modified fields from the detached object to the persisted object. This is extra work.
- Keep a single EntityManager instance alive through the whole process. Unfortunately, other threads could perform CRUD operations while this session is still open, taking the persisted context out of sync with the database table. So I'm not a fan of this approach either.
Is there any good way to do this, or are these the only options available?
The JPA specification defines the merge()
operation. The operation seems to be useful to implement the described use case.
Please refer to the specification:
这篇关于我如何坚持一个分离的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!