Hibernate 中实体集合的陷阱
好的,这是这个问题的后续问题,因为我现在真的很困惑。
假设我在实体 Person
和 Event
之间有一对多或多对多关联,这样 Java 中的 Person
类包含设置
。 (让我们忽略 Event 是否包含单个 Person
还是 Set
。)
Event
是存储在数据库中的实体,因此我可以更改事件字段。 处理 Event
可变性并且不获取 Java Set<> 的正确方法是什么? 身份验证混乱? 在这种情况下,您是否永远不应该重写 hashCode()
和/或 equals()
? (例如,身份 = 基于对象引用身份)
如果我希望对 Event
进行排序(例如,按事件开始时间),如何管理更改 Event
的字段代码>? 一旦更改传播到数据库,数据库就会很好地处理它,但在 Java 方面,这是否意味着为了更改集合中的事件,我必须删除它,更改它,然后重新插入? 或者是否没有真正的方法来维护 Hibernate 映射的 Java 端的排序顺序? (因此,每当我想要获得 Event
的排序列表时,我都必须将其视为无序,因此在 Java 中处理排序?)
编辑: 哎呀,我刚刚发现这些关于 equals/hashCode 的讨论:
OK, this is a follow-up question to this one, since I am really confused now.
Suppose I have a one-to-many or many-to-many association between entities Person
and Event
such that a Person
class in Java contains a Set<Event>
. (Let's ignore whether Event contains a single Person
or a Set<Person>
.)
Event
s are entities stored in a database, therefore I can change the event fields. What's the correct way to handle Event
mutability and not get the Java Set<> identity checking confused? Are you never supposed to override hashCode()
and/or equals()
in this case? (e.g. identity = based on object reference identity)
If I want the Event
s to be ordered (e.g. by an event start time), how do I manage changing the fields of an Event
? The database will handle it fine once the change propagates there, but on the Java side, does that mean in order to change an Event in a collection, I have to remove it, change it, and reinsert? Or is there no real way to maintain a sorted order on the Java side of a Hibernate mapping? (and therefore I have to treat it as unordered and therefore handle sorting in Java whenever I want to get a sorted list of Event
s?)
edit: yuck, I just found these discussions on equals/hashCode:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这根本不是一个陷阱,它强制执行您告诉它期望的语义。
真正的问题是“当我所谓的关键字段发生变化时,平等会发生什么”。 是的,它就在窗外。 所以,是的,你最终可能会遇到这样的情况:有人根据这些键更改了你的集合中的一个字段,使其等于另一个字段。
是的,您的业务逻辑需要处理这个问题。 当您更新事件对象时,您必须确保新值不仅对于字段有效,而且对于您将其放入的上下文也有效。在这种情况下,您不能允许更新的事件对象重复一个现有的事件。
这个问题在 SQL 中更加难看。
It's not a pitfall at all, it's enforcing the semantics you've told it to expect.
The real problem is "What happens to equality when my so-called key fields change". Yes, it goes right out the window. So, yes you can end up in a situation where someone changes a field in your set, that makes it equal to another, based on those keys.
Yes, your business logic needs to handle that. When you update an Event object, you have to make sure that the new values are valid, not only for the field, but the context you're putting them in. In this case you can't allow the event object being updated to duplicate an existing event.
This problem is even uglier in SQL.