Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why do I need to override hashCode() in the @IdClass when using Hibernate  RSS feed

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Can some one please tell me why I need to override hashCode() in the my @IdClass when using composite primary keys?

I do not face any issue when saving and retrieving entities with composite primary keys with out overriding this method.

Can someone tell me a scenario where hashCode implementation is a must?


Thanks in advance,
Amitava
 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why? So that you in the future you don't go insane trying to find an easy to prevent bug.

There are many situations where Hibernate (and yourself) will compare instances of the ID class to see if they are both encapsulating the same primary key. If you don't override both the equals(...) and hashCode() methods you could possibly get a false positive and a false negative. Wrost of all it would probably be very hard to repeat any such problem, thus the bug would be a monster to find. In light of Murphy's Law the bug will most likely show up during a demo with a customer or upper management.

Ran
 
Note to self: don't get into a fist fight with a cactus. Command this tiny ad to do it:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!