【问题标题】:Grails Criteria projections on joined table连接表上的 Grails 标准投影
【发布时间】:2011-08-19 04:49:32
【问题描述】:

我对 grails 标准构建器有疑问,我想对与父表示例一对多关系的表上的列进行投影:

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

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

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

【问题讨论】:

    标签: grails alias projection criteria-api


    【解决方案1】:

    我假设以下域类:

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

    【讨论】:

    • 非常好!在演示前几分钟帮助了我!
    【解决方案2】:

    只做呢:

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

    还是我错过了什么?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-21
      • 2011-04-11
      • 1970-01-01
      • 2015-07-17
      • 2011-08-11
      • 2014-10-03
      相关资源
      最近更新 更多