Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

java - Using auto generated id of Hibernate entity object in the equals and hashcode methods

Lovely equals and hashcode, all the theory is here and also here

I have taken the decision to use the auto-generated id within equals() and hashcode() in a number of my hibernate entity/domain objects.

However, a number of websites say you should never do this due to the risk of persisting an object to the database for the first time whilst it is in the process of being compared or using hashcode.

My point of view is that in most use cases this is much more unlikely than any other field being changed.

The individual domain objects have the id generated once when they are first created, whereas nearly every other field has the opportunity to be altered during normal business processes (even a unique username can be changed ... ).

And in many of my domain objects the unique id is pretty much the only suitable field to be considered (Person, Address, Pet, ... Customer etc etc ? Combining fields is a good idea, but never using the auto generated id is, I think, not good advice.

Am I missing something else ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should read Equals and HashCode on the Hibernate Community Wiki.

The main reason for not using the database identifier in equals, and by implication, hashCode is for dealing with stored, but not persisted, entities. Prior to persistence all you instances are going to be equal, unless you take care to handle that case explicitly.

If you know that you're not going to be in this scenario, and you make sure it's well documented, you may well be OK. You can always change the implementations later.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...