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

equals hashCode furthermore needed?

 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Am I right, that in JPA2 I do not need to overwrite equals/hashCode?

And If yes, am I right, that only the id-field(s) of a class should be considered in the equals/hashCode ?
 
James Sutherland
Ranch Hand
Posts: 553
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not aware of the JPA spec ever requiring you define an equals/hashCode in your Entity objects.

JPA does require you define equals/hashCode in IdClass or EmbeddedId classes. I don't think this requirement has changed in JPA2.

A JPA provider may have additional, or less requirements. (in EclipseLink you do not need to override equals/hashCode in your Entity, or normally even in your IdClass).

If you define an equals/hashCode in your Entity, sticking to Id fields would probably be a good idea, however be careful of null Ids for new objects, you probably don't want all new objects to be equal.
If null maybe revert to identity, or just use identity (Object.equals) in general as JPA preserves object identity within a persistence context.

If you use Sets or Maps ensure your objects hashCode will never change, otherwise this could corrupt the Set/Map's hashing.
 
nimo frey
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you! That helped me!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic