Grails,比较两个对象? [英] Grails, comparing two objects?

查看:84
本文介绍了Grails,比较两个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class客户端{
字符串名字
字符串姓名
字符串中间名
}

然后我有一个表格,母亲不能等于父亲。哪种验证器比较客户端更合适?有什么区别吗?我已经尝试过两种方法,但是我不太确定它是否是巧合。我也可能是错的。如何比较两个对象?任何建议?



val.id == obj.father.id val = = obj.father

  class表格{
客户端母亲
客户端父亲

static constraints = {
mother(nullable:true,validator:{val,obj - >
if(mother等于父){
return [invalid .motherCannotBeEqualFather.label]
}
})
}
}


解决方案

val == obj.father



将导致 val.equals(obj.father),因为Groovy重载==。这个的默认行为是简单地检查引用的相等性,这可能是危险的。 Hibernate会尝试确保平等(请参阅Fabiano的链接),但它可能不可靠。



val.id == obj.father。 id



确保这两个对象表示与您的域对象关联的数据库表中的不同条目。当您保存新的域对象时,Grails会为该对象分配一个在其域中唯一的ID。默认情况下,这是通过在数据库表中增加一个代表对象的id来完成的。



如果在执行此验证时母亲和父亲已经保存到数据库,可能是一个有用的平等检查。



如果您只是试图阻止firstName,lastName和middleName在表单上相同,看起来好像这样只有在客户端域中将这些字段的唯一性约束定义为一个组时,验证才会生效,例如 firstName(unique:['lastName','middleName'])



考虑只定义一个明确的验证器确保您所寻找的独特性。


I have a Client object.

class Client{
String firstName
String lastName
String middleName
}

Then I have a form where mother cannot be equal to father. Which validator would be more proper for comparing the clients? Is there even a difference? I've tried both and they work, though I'm not too sure if it may just be a coincidence. I could be wrong too. How is comparing done for two objects? Any advice?

val.id == obj.father.id or val == obj.father

class Form{
Client mother
Client father

static constraints = {
mother (nullable:true, validator: { val, obj ->
            if(mother equals father){
                return ["invalid.motherCannotBeEqualFather.label"]  
            }
        })
}
}

解决方案

val == obj.father

Will result in val.equals(obj.father), as Groovy overloads ==. The default behavior of this is to simply check for reference equality, which can be dangerous. Hibernate will attempt to ensure equality (see the link by Fabiano), but it can be unreliable.

val.id == obj.father.id

Will ensure that the two objects represent different entries in the database table associated with your domain object. When you save a new domain object, Grails assigns the object an id that is unique within its domain. By default this is accomplished with an incremented id in the DB table representing your object.

If mother and father have already been saved to the DB when this validation is performed, it could be a useful equality check.

If you simply trying to prevent firstName, lastName, and middleName from being the same on a form, which it kind of seems like, this validation will only be effective if you've defined uniqueness constraints on those fields as a group in the client domain, e.g. firstName(unique: ['lastName', 'middleName']).

Consider just defining a validator that explicitly ensures the uniqueness you're looking for.

这篇关于Grails,比较两个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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