简体   繁体   中英

Grails + GORM: What is the default equals() implementation in GORM?

When I do domainObj1 == domainObj2 in Grails are the objects compared by ID? If not, how are they compared?

First, you need to understand that GORM/Grails doesn't do anything special when it comes to equals() . Unless you implement your own equals() on your domain class it will default to the Java/Groovy implementation. Which by default means the variables must point to the same instance.

Now, what gets slightly confusing is Hibernate. Hibernate uses an identity map (the first-level cache); when you fetch the same domain instance from GORM, Hibernate will actually return the same instance from the cache the second time. Thus making the two variables point to the same instance and appear as equal.

For example:

def something = Something.get(1)
def somethingElse = Something.get(1)
assert (something == somethingElse) // true
something.name = 'I changed this'
assert (something == somethingElse) // still true
something.id = 123 // no idea why you would EVER do this
assert (something == somethingElse) // still true
assert (something.id == somethingElse.id) // true, since it's the same instance!
assert (something.name == somethingElse.name) // true, since it's the same 

Even with changes made to the instance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM