Grails / GORM criteria query with hasmany String

2019-02-16 14:36发布

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?

3条回答
对你真心纯属浪费
2楼-- · 2019-02-16 15:04

You can use HQL for querying in such a scenario. For example,

Cat.findAll("from Cat c where :nicknames in elements(c.nicknames)", [nicknames:'kitty'])
查看更多
可以哭但决不认输i
3楼-- · 2019-02-16 15:10

You can also use HQL (tested with Grails 2.5.0):

Cat.findAll("from Cat c inner join c.nicknames as n where upper(n) like '%'||?||'%'", [nickname.toUpperCase()])
查看更多
Ridiculous、
4楼-- · 2019-02-16 15:14

After a lot of trying and researching, I found this will work with Grails 2.4.0, I don't know about older versions.

Cat.withCriteria {
    createAlias('nicknames', 'n') 
    ilike 'n.elements', '%kitty%'
}

The trick is to use 'n.elements'

查看更多
登录 后发表回答