java - Hibernate Entity 在“相同范围”中等于 var null 而不是 null
问题描述
我正在equals
与我的冬眠实体斗争......
或者让我们说:我不知道,为什么 Id在同一范围内Integer id
正确打印,为什么?!toString
System.out.println(id) -> null
我尝试在 entityconfig 中使用lazy
and 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
------------------------------------------------
解决方案
注意日志中工作站的类信息。第一个是您的 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())));
推荐阅读
- c - 在c中从堆栈中读取格式字符串失败
- react-native - React Navigation v5:用于标题屏幕交互的 useEffect()?
- python - 输出尺寸不匹配与 pytorch 中模型摘要报告的内容
- java - 加密或散列
- python - 使用 selenium 优化线程
- javascript - 从 Firebase Firestore 获取图像并将它们添加到“li”
- sql - 我们如何在 oracle 中表示重复的数字?
- python - 当该频道的成员为 0 时,创建私人语音频道并删除该频道
- java - MockMVC 在请求参数中添加带有字符串的附加引号和发布请求
- java - 如何使用 JNA 将 java 原始数组传递给 C dll?