Giannis
Giannis

Reputation: 5526

Grails - HQL to CriteriaBuilder

I have been struggling with understanding how to use criteria builders. On the very simple scenarios they are straight forward. But how would the following HQL be expressed?

def pkg_query = "select p from Package as p join p.orgs as orgRole where p.packageScope=(:scope) and orgRole.roleType=(:roleType) and orgRole.org=(:provider)"

The first part of the query is easy, but how I access the list?

  Package master = c.get {
    and {
        eq("packageScope",getMasterScope())
        //imaginary code, 'and' would probably break it as only 1 match in list
        for(orgRole in orgs){
            and{
                eq(orRole.org,provider)
                eq(orgRole.roleType,getCPRole())
            }
        }
    }
  }

Upvotes: 0

Views: 206

Answers (2)

praveen_programmer
praveen_programmer

Reputation: 1062

You can use below code to get list of object.

def listOfPackage = Package.createCriteria().list {
      eq('packageScope', scope)
      orgs {
         and {
            eq('roleType', roleType)
            eq('org', provider)
         }
      }
    }

Upvotes: 1

Deigote
Deigote

Reputation: 1761

You can model criterias against associations (regardless of their cardinalitiy) by invoking them as a method that receives a closure with the criterias inside. For the query you posted it'd be:

Package.createCriteria().get {
  eq('packageScope', scope)
  orgs {
     and {
        eq('roleType', roleType)
        eq('org', provider)
     }
  }
}

Upvotes: 2

Related Questions