I am working on a grails project and would like to leverage hibernate criteria builders to search for instances of a domain object. I would like to find instances where one of the 'hasMany' relationships contains domain object with certain ids. Here is an example of what I mean.
Domain Objects
class Product {
static hasMany = [ productOptions: ProductOption ]
}
class ProductOption{
Option option
static belongsTo = [ product: Product ]
}
class Option{
String name
}
This is a simplified example of my domain structure and doesn't include all relationships.
An Option
could be size, color, brand, etc.
Example of what I would like to achieve
Lets say I have 3 products.
Product 1 is red, small and by brandx
Product 2 is blue, small and by brandx
Product 3 is yellow, medium and by brandz
I have a few scenarios that I need to cover.
Scenario 1
- Find products that are blue, small and by brandx. So in this case I should only return Product 2.
Scenario 2
- Find products that are either red or blue and size small. So both Product 1 and Product 2 should be returned.
Scenario 3
- Find products that are either by brandx or brandz. So all products should be returned.
I hope this covers all scenarios.
This is an example of a current attempt.
def c = Product.createCriteria()
def products = c.list{
and {
productOptions {
'option' {
idEq(1)//1 is the id of the blue option
}
}
productOptions {
'option' {
idEq(5)//5 is the id of the small size option
}
}
productOptions {
'option' {
idEq(10)//10 is the id of the brandx brand option
}
}
}
}
The and
portion of this example doesn't include all options and fails. How do I best achieve this? Can I use Grails hibernate criteria builder to achieve this? Please let me know if additional information will help.
Thanks in advance for any guidance provided.