在生成id的实体上实现equals()时,最佳实践是什么? [英] What is the best practice when implementing equals() for entities with generated ids
问题描述
的表A:自动生成的ID(PK)
B& C:组合必须是唯一的(这些是在商业意义上实际定义身份的列)
D:其他一些列
现在,如果我将基于此表创建业务对象(例如,在Java中),哪一个更适合执行equals()方法:
- 基于A定义相等性
- 定义基于B和C的相等性
或者,我选择哪一个并不重要。
解决方案肯定是B和C,因为你想要即使在实体持久化之前,
equals()
合约仍然有效。你说自己:
这些是实际上
定义商业意义上的身份的列
如果是这种情况,那么逻辑
equals()
应该使用。数据库密钥是数据库的关注点,应该与业务层无关。
不要忘记在
中使用相同的属性hashcode ()
。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 columnsNow, 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:
- define equality based on A
- define equality based on B and C
or, it wouldn't really matter which of the two I choose.
解决方案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.这篇关于在生成id的实体上实现equals()时,最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!