Grails + GORM:GORM中默认的equals()实现是什么? [英] Grails + GORM: What is the default equals() implementation in GORM?

查看:130
本文介绍了Grails + GORM:GORM中默认的equals()实现是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Grails中执行domainObj1 == domainObj2时,是否按ID比较对象?如果没有,如何比较?

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

推荐答案

首先,您需要了解,对于equals(),GORM/Grails并没有做任何特别的事情.除非您在域类上实现自己的equals(),否则它将默认为Java/Groovy实现.默认情况下,这意味着变量必须指向相同的实例.

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.

现在,有些令人困惑的是Hibernate. Hibernate使用身份映射(一级缓存);当您从GORM获取相同的域实例时,Hibernate实际上将第二次从缓存中返回相同的实例.因此,使这两个变量指向同一实例并显示为相等.

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.

例如:

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 

即使对实例进行了更改

这篇关于Grails + GORM:GORM中默认的equals()实现是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆