问题
When I do domainObj1 == domainObj2
in Grails are the objects compared by ID? If not, how are they compared?
回答1:
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
来源:https://stackoverflow.com/questions/28500091/grails-gorm-what-is-the-default-equals-implementation-in-gorm