views:

114

answers:

1

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>.)

Events 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 Events 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 Events?)

edit: yuck, I just found these discussions on equals/hashCode:

A: 

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.

Jim Barrows