• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Implementing equals and hashCode for entity class

 
Bupjae Lee
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I googled how to implement equals and hashCode for entity class.

There are some advices, but I'm still not sure which is the best solution.

1) Check only @Id field
Drawback: Before persisting, @Id field is null; in this case, there are no way to check equality

2) Check"business identity fields" that won't be changed
Drawback: There is some possiblity that such fields would be changed.

3) Build identity by programmer, not framework
Drawback: It is hard to make unique identity at any situation

Which is better choice? Any other suggestions?
 
Gokul Nanthakumar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bupjae Lee wrote:

1) Check only @Id field
Drawback: Before persisting, @Id field is null; in this case, there are no way to check equality



Once you get the ID (after persisting in your case) only your object becomes complete, if id is the unique identifier for your entity, this is the best candidate.

What you are going to compare with incomplete object? even I dont think you will place it in HashMap without id.
 
Christian Dillinger
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you think an unsaved entity is incomplete? Just because of it's transient state?
Of course there might be use cases where you want to put objects into a hashmap before saving them.
 
Bupjae Lee
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, what I want to do is putting entities to another entity's Set.

However, because of problem I mentioned, I'm using List instead of Set.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic