Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails Criteria projections on joined table

I have an issue with grails criteria builder, I want to do a projection on a column that is on a table that is in one-to-many relation to parent table example:

Car.createCriteria() { 
   projections { 
     property('name') 
     property('wheels.name')// ???? 
   }

   join 'wheels' 
   //or wheels {} ???
}

or something similar exist? I think it is basic propblem with aliases

like image 253
csviri Avatar asked May 05 '11 09:05

csviri


2 Answers

I am assuming the following domain classes:

class Car {
  String name
  static  hasMany = [wheels : Wheel]
}

class Wheel {
  String name
  static belongsTo = [car : Car]
}

I also assume that this is the desired output:

CarName WheelName
Car1    Wheel1
Car1    Wheel2
Car2    Wheel3

In this case you would do this:

void testCarProjectionItg() {
  def car1 = new Car(name: 'Car1').save()
  def car2 = new Car(name: 'Car2').save()

  def wheel1 = new Wheel(name: 'Wheel1')
  def wheel2 = new Wheel(name: 'Wheel2')
  def wheel3 = new Wheel(name: 'Wheel3')

  car1.addToWheels wheel1
  car1.addToWheels wheel2     
  car2.addToWheels wheel3
  wheel1.save()
  wheel2.save()
  wheel3.save()
  car1.save()
  car2.save()

  println Wheel.withCriteria {
    projections {
      property('name')
        car {
          property('name')
        }
    }       
  }
}

--Output from testCarProjectionItg--
[[Wheel1, Car1], [Wheel2, Car1], [Wheel3, Car2]]

I would prefer a HQL query in this case:

println Wheel.executeQuery("select car.name, wheel.name from Car car inner join car.wheels wheel")
--Output from testCarProjectionItg--
[[Car1, Wheel1], [Car1, Wheel2], [Car2, Wheel3]]
like image 28
David Betts Avatar answered Nov 06 '22 01:11

David Betts


what about doing only:

Car.createCriteria().list() { 
    createAlias("wheels","wheelsAlias")
    projections { 
        property('name') 
        property('wheelsAlias.name')
    }
}

Or am I missing something?

like image 118
Gil Avatar answered Nov 06 '22 01:11

Gil