[英]Hibernate/JPA equals() and hashCode() with Lazy loaded Business Identifier
我想知道如何为 Hibernate 实体编写正确的 equals() 和 hashCode(),这些实体与另一个实体具有延迟加载的 ManyToOne 关系,这对于业务密钥很重要。 请注意,我已经阅读了有关此主题的 Hibernate 文档,并且我知道我必须/不应该使用 object id。
为了澄清,这里有一个例子:
public class BusinessEntity implements Serializable
{
//for simplicity, here just the important part
private String s;
@ManyToOne(fetch= FetchType.LAZY )
private ImportantEntity anotherEntity;
@Override
public boolean equals( Object obj )
{
//Here I would like to call something like
// (obj.getAnotherEntity.getName.equals(getAnotherEntity.getName) && obj.getS().equals(getS());
return true;
}
}
当然这只是一个简化的例子。 但我希望我能解释我的情况。 以前有人尝试过这样的事情吗? 我没有找到有关此主题的任何内容。
为简单起见,我跳过了空安全代码。 但是这个想法是创建额外的属性,它将保留实体名称并且不会将其暴露给外界
public class BusinessEntity implements Serializable
{
//for simplicity, here just the important part
private String s;
@ManyToOne(fetch= FetchType.LAZY )
private ImportantEntity anotherEntity;
private String anotherEntityName;
@Override
public boolean equals( Object obj )
{
if(BusinessEntity.class.isAssignableFrom(obj.getClasS())){
BusinessEntity other = (BusinessEntity)obj;
return other.anotherEntityName.
equals(this.anotherEntityName) &&
other.s.equals(this.s);
}
return true;
}
public void setAnotherEntity(ImportantEntity ie){
anotherEntityName= ie.getName();
anotherEntity = ie;
}
}
在 equals 中,您应该使用 instanceof 来比较需要包含的属性的类型和 getter。
使用 instanceof 是因为 hibernate 使用的代理类和 getter 用于启用延迟加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.