使用 hasmany 字符串进行 Grails / GORM 条件查询
我有一个像这样的域对象(猫):(
class Cat {
String name
static hasMany = [
nicknames: String
]
}
一只猫有一个名字,并且也有许多昵称(它们是字符串))
并且我正在尝试查询具有某些昵称的所有猫。
我已经尝试过:
PagedResultList getCatsByNickname(String nickname, Map params) {
PagedResultList results = Cat.createCriteria().list(params) {
'ilike'('nicknames','%'+nickname+'%')
}
return results
}
但它永远不会返回任何结果。 (如果我将查询更改为仅使用简单的名称属性,它可以查找具有该名称的所有猫,但我想查询昵称。)
我也尝试了这个:
PagedResultList getCatsByNickname(String nickname, Map params) {
PagedResultList results = Cat.createCriteria().list(params) {
'nicknames' {
'ilike'('nicknames','%'+nickname+'%')
}
}
return results
}
但我收到错误:org.hibernate.MappingException:集合不是关联: example.Cat.nicknames
所以问题是,如何查询 String 类型的 hasMany ?
I have a domain object (Cat) like this:
class Cat {
String name
static hasMany = [
nicknames: String
]
}
(A cat has a name, and also has many nicknames (which are Strings))
And I am trying to query all the cats with certain nicknames.
I've tried this:
PagedResultList getCatsByNickname(String nickname, Map params) {
PagedResultList results = Cat.createCriteria().list(params) {
'ilike'('nicknames','%'+nickname+'%')
}
return results
}
But it never returns any results. (If I change the query to just use the simple name attribute, it works finding all cats with that name, but I want to query against the nicknames.)
I also tried this:
PagedResultList getCatsByNickname(String nickname, Map params) {
PagedResultList results = Cat.createCriteria().list(params) {
'nicknames' {
'ilike'('nicknames','%'+nickname+'%')
}
}
return results
}
But I get the error: org.hibernate.MappingException: collection was not an association: example.Cat.nicknames
So the question is, how do I query against a hasMany of type String?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
经过大量的尝试和研究,我发现这适用于 Grails 2.4.0,我不知道旧版本是否有效。
诀窍是使用“n.元素”
After a lot of trying and researching, I found this will work with Grails 2.4.0, I don't know about older versions.
The trick is to use 'n.elements'
这种场景可以使用HQL进行查询。例如,
You can use HQL for querying in such a scenario. For example,
您还可以使用 HQL(使用 Grails 2.5.0 进行测试):
You can also use HQL (tested with Grails 2.5.0):