简体   繁体   English

Hibernate中实体集合的陷阱

[英]pitfalls of collections of entities in Hibernate

OK, this is a follow-up question to this one , since I am really confused now. OK,这是一个后续问题这一个 ,因为我现在真的混淆。

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> . 假设我在实体PersonEvent之间存在一对多或多对多关联,因此Java中的Person类包含Set<Event> (Let's ignore whether Event contains a single Person or a Set<Person> .) (让我们忽略Event是包含单个Person还是Set<Person> 。)

Event s are entities stored in a database, therefore I can change the event fields. Event s是存储在数据库中的实体,因此我可以更改事件字段。 What's the correct way to handle Event mutability and not get the Java Set<> identity checking confused? 什么是处理Event可变性且不会混淆Java Set <>身份检查的正确方法? Are you never supposed to override hashCode() and/or equals() in this case? 在这种情况下,您决不应该重写hashCode()和/或equals()吗? (eg identity = based on object reference identity) (例如,身份=基于对象引用身份)

If I want the Event s to be ordered (eg by an event start time), how do I manage changing the fields of an Event ? 如果我希望对Event进行排序(例如,按事件开始时间排序),我该如何管理更改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? 一旦更改传播到那里,数据库将很好地处理它,但是在Java方面,这是否意味着要更改集合中的Event,我必须将其删除,更改并重新插入? Or is there no real way to maintain a sorted order on the Java side of a Hibernate mapping? 还是没有真正的方法可以在Hibernate映射的Java端维护排序顺序? (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?) (因此,我必须将其视为无序的,因此每当我想获取Event的排序列表时,都使用Java处理排序?)

edit: yuck, I just found these discussions on equals/hashCode: 编辑:糟糕,我刚刚在equals / hashCode上找到了这些讨论:

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. 在SQL中,此问题更为严重。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM