Grails / GORM criteria query with hasmany String

我只是一个虾纸丫 提交于 2019-12-30 08:09:10

问题


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?


回答1:


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'




回答2:


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'])



回答3:


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()])


来源:https://stackoverflow.com/questions/7531011/grails-gorm-criteria-query-with-hasmany-string

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