Search code examples
grailsgrails-orm

Equals for domain class in grails


The following equals code returns wrong result for domain

boolean equals(o) {
  if (o == null) return false
  if (this.is(o)) return true
  getClass() == o.class && id == o.id
}

For two loaded entities with same id return false. Id are equals (one record in DB). But classes not same.

The entities -- fields in another domains. And it looks like GORM used some wrapper classes.

How to avoid this kind of problem?


Solution

  • Where is special method in GormInstanceApi

    /**
     * Proxy aware instanceOf implementation.
     */
    boolean instanceOf(D o, Class cls) {
        if (o instanceof EntityProxy) {
            o = (D)((EntityProxy)o).getTarget()
        }
        return o in cls
    }
    

    Using of this method solved problem