I have read and taken part in this discussion: <http://www.hibernate.org/109.html> which didn't really come up with any "patent-solution". So I thought that maybee you guys hanging around here might have some answers. The main problem is that you can't generate a hashcode using the values of the objects fields since they may change (when an object is edited) and thus breaks the equals / hashcode convention. I see three main solutions to this:
- Let equals and hashcode depend on the id. This means that if you use an id generated by the db you have to save the object to the database before you can use it in any set. (The id would change when saved to database) This sucks.
- Don't use the id in equals but only compare the fields and set the hashcode to 0. Now all hashSets more or less becomes linked lists. This sucks.
- My own desperate solution: When creating an object generate a random hashcode and persist it with the object. And don't use the id for equals because the id is 0 until the objects are stored when using the database for generating unique ids. This means that the database contains a nonunique random number for each item. This doesn't exactly suck but it sure ain't pretty.