我在 hibernate 实体中遇到 equals
问题...
或者说:我不知道,为什么 Id Integer id
在 toString
中正确打印但在同一范围 System.out.println(id) -> null
为什么?!
我尝试在 entityconfig 中使用 lazy
和 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
------------------------------------------------
最佳答案
注意日志中工作站的类信息。第一个是您的工作站类,另一个是 Hibernate 生成的工作站类的代理。
THIS: class com.wulf.system.mes.model.Workstation
O: class com.wulf.system.mes.model.Workstation$HibernateProxy$ycosLiwl
Hibernate 生成的代理类将其所有方法调用委托(delegate)给目标对象。因此,当调用 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())));
关于java - Hibernate 实体等于 var null 而不是 "same scope"中的 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63767883/