开发者

Hibernate/JPA equals() and hashCode() with Lazy loaded Business Identifier

I'm wondering how to write a correct equals() and hashCode() for Hibernate Entities which have a Lazy Loaded ManyToOne relation to another Entity which is important as a business key. Note, that I already read the Hibernate documentation on this topic and I know I must/should not use the object id.

To clarify, here an example:

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;
    }
}

Of course this is just a simplified example. But I hope I could explain my scenario. Has someone tried something like that before? I did not find anything regarding to this topic.


For simplicity I have skipped null-safety code. But the idea is to create additional property which will persist entity name and will not expose it to the outside world

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;
    }
}


In the equals you should use instanceof to compare types and the getters of the properties that you need to include.

instanceof is used because of the proxy classes that hibernate uses and the getters are used to enable lazy loads.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜