根据此 Link
The gist of it is you only need to worry about it if your entity will be part of a Set(condition 1) or/And if you're going to be detaching / attaching its instances.(condition2)
根据我的理解,我们只需要条件 1,其中需要 hashcode 和 equals 方法实现
如果我有一个要求,我不想存储重复的客户(基于客户名称)或检索重复的客户 来自 hibernate api 的客户(用于遗留数据),那么我的理解是将客户存储在集合下确实在这里有意义 这是我们唯一需要实现 hashcode 和 equals 方法的场景。
我不明白当我们要分离/附加其实例(条件)时,哈希码和相等的实现有何帮助
更新:-为了确认我尝试重新附加分离的实例,如下所示
person detached instance lying here for id 1// person overrides hashcode and equals method
session = factory.openSession();
tx = session.beginTransaction();
person1=(Person)session.get(Person.class, 1);
session.lock(person, LockMode.NONE);// reattaching the detached instance here
// as per Marko Topolnik comment i was expecting equality will be checked based on equals and hashcode
// method but it was done based on person id . so question is does hashcode and equals come into picture
// while reattaching the detached instance
tx.commit();
最佳答案
分离和附加依赖于@id。不要依赖错误的答案,正确的答案是您提供的链接中的第二个答案(由 Phil 撰写)。
You only need to override equals() and hashcode() if the entity will be used in a Set (which is very common) AND the entity will be detached from, and subsequently re-attached to, hibernate sessions (which is an uncommon usage of hibernate).
- intend to put instances of persistent classes in a Set (the recommended way to represent many-valued associations); and
- intend to use reattachment of detached instances
这意味着如果您打算重新附加存储在父实体中的 Set 中的实体。 因此,只有当两个条件同时为真时,hibernate才需要实现Hashcode和Equals。
此外,当您使用复合主键时,实现 equals 和 hashCode 是一个好主意,如 composite id section 中所述。
关于java - hibernate下什么时候需要实现Hashcode和Equals?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22172430/