Hibernate/JPA等于()和带有延迟加载的业务标识符的hashCode()

Dom*_*ier 6 java hibernate jpa lazy-loading equals

我想知道如何为Hibernate实体编写正确的equals()和hashCode(),这些实体具有与另一个实体的Lazy Loaded ManyToOne关系,这对于作为业务键很重要.注意,我已经阅读了关于这个主题的Hibernate文档,我知道我必须/不应该使用对象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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,这只是一个简化的例子.但我希望我能解释一下我的情景.以前有人试过类似的东西吗?我没有找到关于这个主题的任何内容.

Mar*_*ski 3

为了简单起见,我跳过了空安全代码。但我们的想法是创建额外的属性,该属性将保留实体名称并且不会将其暴露给外界

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;
    }
}
Run Code Online (Sandbox Code Playgroud)