Search code examples
grailsgrails-ormcriteria

How can I join table with criteria in grails, if i have not link fields in my domain class


I have two classes in domain model:

class Project {
   String name
   Integer fund
}

class Task {
   String name
   Integer weight
   Project project
}

How can I get Project with Task.name = "something"?

If i need Task with Project.name = "something", I can do it with criteria by createAlias, but how can I join Task in

c = Project.createCriteria()
   criteriaRes = c.list {
}

Solution

  • I'm not sure if this will be helpful, but I've worked a lot with SQL so when I'm stuck figuring out how to create a criteria or where query I do it first in HQL since it's similar to SQL. If you don't plan on using a NoSQL database HQL is a good choice, but criteria and where queries are portable across GORM implementations.

    So an HQL query that does what you want is

    def projects = Task.executeQuery(
       'select t.project from Task t where t.name=:taskName',
       [taskName: 'something'])
    

    An analagous criteria query would then be

    def projects = Task.createCriteria().list {
       eq 'name', 'something'
       projections {
          property 'project'
       }
    }