gpt4 book ai didi

java - 使用 equals/hashCode 比较延迟加载的 Spring Data MongoDB 实体

转载 作者:行者123 更新时间:2023-11-30 10:43:41 25 4
gpt4 key购买 nike

我有两个对象

  • 懒加载

      product:5757b95d1d8eecdd01e59b29$LazyLoadingProxy
  • 其他eager加载

      com.entity.Product@5e6c4568

我知道这两个对象是相同的,因为它们具有相同的唯一 ID (id=5757b95d1d8eecdd01e59b29)。

我的 Product 类中有以下方法:

  @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((id == null) ? 0 : id.hashCode());
return result;
}

@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Item other = (Item) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}

但是现在当我执行以下操作时,我找不到匹配项。有什么线索吗?

temp.contains(product) == false

temp 包含延迟加载项,product 包含普通项。

最佳答案

简而言之

这就是您实现 equals 的方式。

解释

Spring Data MongoDB 使用代码生成库创建延迟加载代理。运行时延迟加载引用的类类似于 com.example.Product$$EnhancerByCGLIB$$5f3cdccd。您的实现会检查确切的类类型

if (getClass() != obj.getClass()) {
return false;
}

导致 equals 返回 false。一个更友好的支票版本是:

if (!(o instanceof Product)) {
return false;
}

还请注意,根据集合中的实例以及传递给 contains() 的实例,equalshashCode 方法在代理实例或实体类上调用。这与 id 检查无关,因为 id 字段始终被填充,但如果您尝试比较其他属性,它就会变得相关。背后的原因是代理字段没有初始化(也不会被初始化),因为解析的对象是分开的。这意味着比较 id 以外的属性需要调用它们的 getter。

关于java - 使用 equals/hashCode 比较延迟加载的 Spring Data MongoDB 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37694796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com