使用 Hibernate 在表中仅保留不同的值
我正在数据库中存储一个相对复杂的不可变对象。有许多多对一的关联——对象有属性,对象有属性等等。
我希望每个对象仅存储一次,基于业务密钥,在本例中是对象的每个属性。
工作流程是这样的:
- 用户创建一个复杂的对象。这可能需要很长时间,代码都分散在各处。
- 我查询数据库,查看之前是否已经存储了完全相同的对象:
- 如果没有,
保存
- 如果是,请设置对象的 id 并
合并
- 如果没有,
问题是 Hibernate 的 merge
有相当不方便的语义
transientObject = createComplexTransientObject();
mergedObject = session.merge(transientObject);
// here you have to discard transientObject
// use mergedObject from now on
:创建的对象必须被丢弃并替换为 Hibernate 提供的对象,这意味着我必须更新对它的所有引用。
我需要一种方法来告诉 hibernate:“这个全新的瞬态对象似乎与数据库中已有的对象相同。将其合并到位。”换句话说:
object = createComplexTransientObject();
session.inPlaceMerge(object);
// object is now persistent
我怎样才能实现这一目标?
I am storing a relatively complex immutable object in a database. There are many many-to-one associations - the object has properties that have properties and so on.
I would like to have each object stored only once, based on a business key that is in this case every single property of the object.
The workflow is like this:
- user creates a complex object. This can take a long time, code is all scattered over the place.
- I query the database, to see if the exact same object was already stored before:
- if not,
save
- if yes, set the object's id and
merge
- if not,
The problem is that Hibernate's merge
has quite inconvenient semantics:
transientObject = createComplexTransientObject();
mergedObject = session.merge(transientObject);
// here you have to discard transientObject
// use mergedObject from now on
The object that got created has to be discarded and replaced with the one provided by Hibernate, which means I have to update all references to it.
I need a way to tell hibernate: "This completely new transientObject appears to be identical to one that is already in the database. Merge it in place." In other words:
object = createComplexTransientObject();
session.inPlaceMerge(object);
// object is now persistent
How can I achieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信 saveOrUpdate 正是您想要的。但它的行为也取决于您的映射。
如果您执行 saveOrUpdate,它会给出您期望的结果吗?
这里有点题外话:你知道按示例查询吗? http://docs.jboss.org /hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-examples
没关系。我才看到这个问题已经两年了。愚蠢的“相关问题”- stackoverflow 的选项。
I believe saveOrUpdate does exactly what you want. But its behavior also depends on your mapping.
If you do saveOrUpdate, does it give you the results you expect?
A bit off-topic here: do you know about Query By Example? http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-examples
Never mind. I just see this question is two years old. Stupid 'related questions'-option of stackoverflow.