开发者

Search records having comma seperated values that contains any element from the given list

I ha开发者_Python百科ve a domain class Schedule with a property 'days' holding comma separated values like '2,5,6,8,9'.

Class Schedule {
   String days
   ...
}

Schedule schedule1 = new Schedule(days :'2,5,6,8,9')
schedule1.save()

Schedule schedule2 = new Schedule(days :'1,5,9,13')
schedule2.save()

I need to get the list of the schedules having any day from the given list say [2,8,11].

Output: [schedule1]

How do I write the criteria query or HQL for the same. We can prefix & suffix the days with comma like ',2,5,6,8,9,' if that helps.

Thanks,


Hope you have a good reason for such denormalization - otherwise it would be better to save the list to a child table.

Otherwise, querying would be complicated. Like:

  def days = [2,8,11]
  // note to check for empty days
  Schedule.withCriteria {
    days.each { day ->
      or {
        like('username', "$day,%") // starts with "$day"
        like('username', "%,$day,%")
        like('username', "%,$day") // ends with "$day"
      }
    }
  }


In MySQL there is a SET datatype and FIND_IN_SET function, but I've never used that with Grails. Some databases have support for standard SQL2003 ARRAY datatype for storing arrays in a field. It's possible to map them using hibernate usertypes (which are supported in Grails).

If you are using MySQL, FIND_IN_SET query should work with the Criteria API sqlRestriction: http://grails.org/doc/latest/api/grails/orm/HibernateCriteriaBuilder.html#sqlRestriction(java.lang.String) Using SET+FIND_IN_SET makes the queries a bit more efficient than like queries if you care about performance and have a real requirement to do denormalization.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜