在生成id的实体上实现equals()时,最佳实践是什么? [英] What is the best practice when implementing equals() for entities with generated ids

查看:75
本文介绍了在生成id的实体上实现equals()时,最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个列A,B,C,D
的表A:自动生成的ID(PK)
B& C:组合必须是唯一的(这些是在商业意义上实际定义身份的列)

  D:其他一些列

现在,如果我将基于此表创建业务对象(例如,在Java中),哪一个更适合执行equals()方法:


  1. 基于A定义相等性

  2. 定义基于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 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.

    解决方案

    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆