Have multiple domain which connected with each other. Need to provide deep search functionality, so that need to search in Master domain’s 3-d and 4-th level children. For example we have structure like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Person {
  static hasMany = [clothes:Cloth]
...
}
 
class Cloth {
  Color color
...
}
 
class Color {
  String name
  ...
}

And we have several Persons with different sets of Clothes in different Colors.
We want to find all people who has red Cloth. It can be often the case that Same Person has several Clothes that are red.
So query like:

1
2
3
4
5
6
7
8
9
10
11
def color = params.color
Person.createCriteria().list{
  clothes {
    color {
      ilike('name', "%${color}%")
    }
  }
  maxResults(params.max as Integer)
  firstResult(params.offset as Integer)
  cache true  
}

Will return paged results but with several same people. So we need to use distict list to have correct results.
BUT!
Grails docs states that

The listDistinct() method does not work well with the pagination options maxResult and firstResult. If you need distinct results with pagination, we currently recommend that you use HQL.

And honestly I do not like HQL very much.
So after some time of playing wit Google, Hibernate and grails DSL, solution was found:

1
2
3
4
5
6
7
8
9
10
11
12
13
Person.createCriteria().list {
  projections {
    groupProperty('id')
  }
  clothes {
    color {
      ilike('name', "%${color}%")
    }
  }
  maxResults(params.max as Integer)
  firstResult(params.offset as Integer)
  cache true
}.collect {Person.get(it[0])}

Maybe a little ugly but resolve problem with pagination on distinct elems 100%.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

1,854 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2012 REID Consulting Suffusion theme by Sayontan Sinha