连接表上的Grails Criteria投影

时间:2011-05-05 09:00:10

标签: grails alias projection criteria-api

我的grails条件构建器存在问题,我想对与父表示例一对多关系的表上的列进行投影:

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

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

或类似的东西存在?我认为这是别名的基本问题

2 个答案:

答案 0 :(得分:21)

我假设以下域类:

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

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

我还假设这是所需的输出:

CarName WheelName
Car1    Wheel1
Car1    Wheel2
Car2    Wheel3

在这种情况下,你会这样做:

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]]

在这种情况下我更喜欢HQL查询:

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]]

答案 1 :(得分:9)

仅限于做什么:

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

或者我错过了什么?