[hibernate-issues] [Hibernate-JIRA] Commented: (HHH-3771) Best pactice for equals implementation?

Samppa Saarela (JIRA) noreply at atlassian.com
Tue Feb 10 06:02:38 EST 2009


    [ http://opensource.atlassian.com/projects/hibernate/browse/HHH-3771?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=32349#action_32349 ] 

Samppa Saarela commented on HHH-3771:
-------------------------------------

Without direct support from Hibernate and if one doesn't want to bind entity classes so tightly to Hibernate, an alternative approach usable in domain classes is 

public final class Ref<T> {
    public final T value;
    public Ref(T value) {
        this.value = value;
    }
}

public abstract class ReferenceEquality<T> {
    
    @Override
    public boolean equals(Object o) {
        if (o instanceof ReferenceEquality) {
            @SuppressWarnings("unchecked")
            ReferenceEquality e = (ReferenceEquality) o;
            return this == e.getReference().value;
        }
        return false;
    }
    
    @SuppressWarnings("unchecked")
    public Ref<T> getReference() {
        return new Ref(this);
    }
    
}

> Best pactice for equals implementation?
> ---------------------------------------
>
>                 Key: HHH-3771
>                 URL: http://opensource.atlassian.com/projects/hibernate/browse/HHH-3771
>             Project: Hibernate Core
>          Issue Type: New Feature
>          Components: core, documentation
>            Reporter: Samppa Saarela
>
> When domain model contains even one lazy reference to an object, default equals fails when it's compared to a) the actual implementation returned by Session.get/load or b) other proxies (at least of different supertype). Overriding equals on a class that uses surrogate id is not that simple. However there is a simple solution to this problem: 
> In domain class, override equals like this:
> public boolean equals(Object obj) {
>   return this == getImplementation(obj);
> }
> public static Object getImplementation(Object obj) {
>   if (obj instanceof HibernateProxy) {
>     return ((HibernateProxy) obj).getHibernateLazyInitializer().getImplementation();
>   } else {
>     return obj; 
>   }
> }
> This should result always in comparing object references of actual instances and thus preserve symmetry.
> It's understandable that you don't wan to publish that kind of getImplementation utility e.g. in Hibernate, but maybe you could support this more directly by implementing 
> Hibernate.equals(Object o1, Object o2) 

-- 
This message is automatically generated by JIRA.
-
If you think it was sent incorrectly contact one of the administrators: http://opensource.atlassian.com/projects/hibernate/secure/Administrators.jspa
-
For more information on JIRA, see: http://www.atlassian.com/software/jira

        



More information about the hibernate-issues mailing list