如何解决休眠实体在“相同范围”中等于var null而不是null
我与休眠实体在equals
之间挣扎...
还是让我们说:我不知道为什么Integer id
的ID toString
可以正确打印,但在System.out.println(id) -> null
的相同范围内为什么?!
我在实体配置中尝试使用lazy
和eager
进行bouth,但是行为相同。
那是我的课:
@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的类信息。第一个是您的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值。休眠代理类上的字段值始终为空。
解决方案
使用getter方法。
System.out.println("THAT ID: " + that.getId());
System.out.println("ERGEBNIS: " + (id.equals(that.getId())));
,
所以答案很简单-对象没有保存到数据库中。在toString()中调用ID时,不会生成ID。
因此,请尝试先保存实体,然后执行其findById作为示例并调用toString。我坚信在这种情况下我不会为空。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。