0

I am using Grails 2.2.4 to build a web application, and now I am having a complex problem with Grails withCriteria operation. I have 3 classes as below:

class Person {
    int id
    String name
    Set<Car> cars = []  // One-to-many relationship
    Company currentCompany // One-to-one relationship
}

class Car {
    int id
    String manufacturer
    String brand
    double price
    Person owner
}

class Company {
    int id
    String name
    Set<Person> employees = []
}

And now I want to query data from Person as root class along with associated data like this:

List result = Person.withCriteria {
    projections {
        property('id')
        property('name')
        createAlias('cars', 'c', CriteriaSpecification.LEFT_JOIN)
        property('c.brand')
        createAlias('currentCompany', 'com', CriteriaSpecification.LEFT_JOIN)
        property('com.name')
    }
        lt('id', 10L)
        resultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
}

And the problem is, I don't know how to transform deeply the result data to a List of persons to make sure every single element contains its data as the class structure. I tried many methods like

    resultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
    resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
    resultTransformer(CriteriaSpecification.aliasToBean(Person.class))  

but nothing worked as I expected.
Does Grails 2.2.4 support this? If yes so what is the correct syntax?
Thank you so much.

Đinh Hồng Châu
  • 5,300
  • 15
  • 53
  • 90
  • Have you also tried using `createCriteria` instead of `withCriteria`? – dmahapatro Dec 30 '13 at 16:43
  • Yes I have, and nothing else happened. As I know Grails does not support transforming result data to domain class directly when if criteria contains projection. So I think in this case I should implement it manually. – Đinh Hồng Châu Dec 30 '13 at 17:08
  • If you want, you can have a custom ResultTransformer according to your need. Here is an [example](http://bethecoder.com/applications/tutorials/hibernate/hibernate-query-language/custom-result-transformer.html) in JAVA. – dmahapatro Dec 30 '13 at 17:35

1 Answers1

0

Actually, after researching many articles, Grails documentation and even its source code, I think the best way to do this is implementing a custom transformer for my own purpose. The most difficult thing here is how to transform data to association objects and gather them to collection inside the root entity. And I have created one here: http://www.mycodestock.com/code/10333/
Hope it helps you guys who may need something like mine.

Đinh Hồng Châu
  • 5,300
  • 15
  • 53
  • 90