首页 > 解决方案 > Hibernate Entity 在“相同范围”中等于 var null 而不是 null

问题描述

我正在equals与我的冬眠实体斗争......

或者让我们说:我不知道,为什么 Id在同一范围内Integer id正确打印,为什么?!toStringSystem.out.println(id) -> null

我尝试在 entityconfig 中使用lazyand eager,但行为相同。

那是我的课:

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
.....
@Override
    public boolean equals(Object o) {
        System.out.println("------------------------------------------------");
        System.out.println("THIS: " + getClass().toString());
        System.out.println("O: " + o.getClass().toString());
        System.out.println("THIS: " + getClass().getClassLoader().toString());
        System.out.println("O: " + o.getClass().getClassLoader().toString());

        if (this == o)
            return true;
        if (o == null)
            return false;
        if(!(o instanceof Workstation)){
            return false;
        }
        Workstation that = (Workstation) o;
        System.out.println("THIS TO STRING: " + this.toString());
        System.out.println("THAT TO STRING: " + that.toString());
        System.out.println("THIS ID: " + this.id);
        System.out.println("THAT ID: " + that.id);
        System.out.println("THIS ID: " + this.id + " T");
        System.out.println("THAT ID: " + that.id + " T");
        System.out.println("ERGEBNIS: " + (id.equals(that.id)));
        System.out.println("------------------------------------------------");
        return id.equals(that.id);
    }

    @Override
    public String toString() {
        if (name != null)
            return id + " - " + name + " ";
        return "FEHLER WORKSTATION";
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

就是这样:

------------------------------------------------
THIS: class com.wulf.system.mes.model.Workstation
O: class com.wulf.system.mes.model.Workstation$HibernateProxy$ycosLiwl
THIS: org.springframework.boot.devtools.restart.classloader.RestartClassLoader@66e4c786
O: org.springframework.boot.devtools.restart.classloader.RestartClassLoader@66e4c786
THIS TO STRING: 5 - Zuschnitt <- TO STRING
THAT TO STRING: 5 - Zuschnitt <- TO STRING -- ID is 5 BUT
THIS ID: 5
THAT ID: null <- if I want to print the id of Object "That" I get null WHY?!
THIS ID: 5 T
THAT ID: null T
ERGEBNIS: false
------------------------------------------------

标签: javahibernateequals

解决方案


注意日志中工作站的类信息。第一个是您的 Workstation 类,另一个是由 Hibernate 生成的 Workstation 类的代理。

THIS: class com.wulf.system.mes.model.Workstation
O: class com.wulf.system.mes.model.Workstation$HibernateProxy$ycosLiwl

Hibernate 生成的代理类将它的所有方法调用委托给目标对象。因此,当调用 toString 方法时,它会调用真实 Workstation 对象的 toString 方法。真正的工作站对象确实有 id 和 name 值并打印出来。

另一方面,当调用 that.id 时,它会尝试并获取代理类上的 id 值。hibernate 代理类上的字段值始终为空。

解决方案

使用 getter 方法。

System.out.println("THAT ID: " + that.getId());
System.out.println("ERGEBNIS: " + (id.equals(that.getId())));

推荐阅读