我有一个实体POJO,它具有item和location属性,用于hashcode和equals。
List<POJO> pojos = pojoRepository.findAll();然后创建一个查找POJO对象,
POJO pojo = new POJO(item, location);但是,当我尝试执行pojos.contains(pojo)时,它返回false。所以我在pojo equals方法中放置了一个调试信息。
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass()) {
System.err.println("xxxxxxxxxx");
System.err.println(getClass());
System.err.println(obj.getClass());
System.err.println("xxxxxxxxxx");
return false;
}输出回报
xxxxxxxxxx
class com.demo.entity.Pojo
class com.demo.entity.Pojo_$$_jvst83f_19
xxxxxxxxxx如何使其平等?我也尝试过obj instanceof Pojo,但仍然返回false。
发布于 2018-05-16 07:20:12
这是因为hibernate内部创建了proxy类。查询返回的是模拟实体类型的代理实例。这就是为什么不是Pojo而是内部代理类_jvst83f_19的原因。
跳过类比较,只比较属性。
你也可以尝试这样的方法:
getClass().inInstance(obj)发布于 2018-09-14 17:44:48
首先,使用实例代替比较getClass。
其次,在字段中使用getter。在这种情况下,hibernate解析数据库中的数据。
您可以尝试以下实现:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ThisType)) return false;
ThisType other = (ThisType) o;
return getPrimaryKey() != null ? getPrimaryKey().equals(other.getPrimaryKey()) : other.getPrimaryKey() == null;
}ThisType -您的类类型
getPrimaryKey() -获取该类的“主键”。通常由@Id注释
https://stackoverflow.com/questions/50364587
复制相似问题