• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Junilu Lacar
  • Liutauras Vilda
Sheriffs:
  • Paul Clapham
  • Jeanne Boyarsky
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
Bartenders:
  • Jesse Duncan
  • Frits Walraven
  • Mikalai Zaikin

Implementing equals and hashCode for entity class

 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic