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
319 views
in Technique[技术] by (71.8m points)

java - What is the best practice when implementing equals() for entities with generated ids

If I have a table with columns A, B, C, D
 A: auto-generated id (PK)
 B & C: combination must be unique (these are the columns that actually define identity in the business sense)
 D: some other columns

Now, if I'll create business objects based on this table (e.g. in Java), which one would be a better implementation of the equals() method:

  1. define equality based on A
  2. define equality based on B and C

or, it wouldn't really matter which of the two I choose.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Definitely B and C, because you want the equals() contract to be valid even before entities are persisted. You say yourself:

these are the columns that actually define identity in the business sense

If that is the case, then that is the logic equals() should use. Database keys are the database's concern and should be of no concern to your business layer.

And don't forget to use the same properties in hashcode(), too.


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

...