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

强颜欢笑 提交于 2019-12-13 11:36:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!