Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Amitav Chowdhury
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
 
Ran Pleasant
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic