Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Hibernate JPA等于POJO_Java_Hibernate_Jpa - Fatal编程技术网

Java Hibernate JPA等于POJO

Java Hibernate JPA等于POJO,java,hibernate,jpa,Java,Hibernate,Jpa,我有一个实体POJO,它的item和location属性用于hashcode和equals List<POJO> pojos = pojoRepository.findAll(); 但是当我尝试执行pojos.containspojo时,它返回false。 所以我在pojo equals方法中放了一个调试信息 产出回报 xxxxxxxxxx class com.demo.entity.Pojo class com.demo.entity.Pojo_$$_jvst83f_19 xxx

我有一个实体POJO,它的item和location属性用于hashcode和equals

List<POJO> pojos = pojoRepository.findAll();
但是当我尝试执行pojos.containspojo时,它返回false。 所以我在pojo equals方法中放了一个调试信息

产出回报

xxxxxxxxxx
class com.demo.entity.Pojo
class com.demo.entity.Pojo_$$_jvst83f_19
xxxxxxxxxx

如何使其平等?我还尝试了Pojo的obj instanceof,但仍然返回false。

这是因为hibernate在内部创建了代理类。查询返回的是模仿实体类型的代理实例。这就是为什么它不是Pojo,而是内部代理类_jvst83f_19

跳过类比较并仅比较属性

您也可以尝试类似的方法:

getClass().inInstance(obj)
首先,使用instanceof而不是比较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注释是的,但是为了使它相等,这里的工作是什么呢?嗯。。这将使我在开发上加倍努力,因为所有实体都是使用eclipse生成的。这取决于方法。您可以使用hack,比如使用unwrap来检索实际的代理对象,但这是一种hack。依我看,你应该只依赖生成的哈希代码。其他更可行的方法是使用样板代码拆卸工具,如lombok,它可以动态生成你需要的东西。你可以使用代码来获取真实的对象。这有点整洁,但会添加额外的检查动态代理。试试我的博客
getClass().inInstance(obj)
@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;
}