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

时间:2011-06-08 21:06:27

标签: java hibernate jpa lazy-loading equals

我想知道如何为Hibernate实体编写正确的equals()和hashCode(),这些实体具有与另一个实体的Lazy Loaded ManyToOne关系,这对于作为业务键很重要。请注意,我已经阅读the Hibernate documentation on this topic,我知道我必须/不应该使用对象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;
    }
}

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

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:2)

在equals中,您应该使用instanceof来比较类型和需要包含的属性的getter。

使用了instanceof,因为hibernate使用的代理类和getter用于启用延迟加载。