2015-02-12 77 views
-3

我有這樣一個域名:Groovy的名稱查詢

ZZPartAndTeam 
    String parts 
    String team  

零件可能會有很多的球隊。

For ex: part:part1 team:10 
     part:part1 team:20 
     part:part2 team:30 

如何在域中查詢獲得所有具有多團隊的零件?

result:part:part1 team:10 
     part:part1 team:20 

謝謝。

+2

到目前爲止您嘗試過什麼?什麼是「多個團隊」?你的「域」有'字符串部分',稍後你會談論'部分:'。這個例子不完全難以理解 – cfrick 2015-02-12 09:23:54

回答

0

Hibernate條件不支持HAVING子句。解決方法是使用DetachedCriteria。

  import org.hibernate.criterion.DetachedCriteria as HDetachedCriteria 

      query: { builder, params -> 

       // This query counts the number of teams per part 
       HDetachedCriteria innerQry = HDetachedCriteria.forClass(ZZPartAndTeam.class) 
       innerQry.setProjection(Projections.projectionList() 
        .add(Projections.count('team').as('teamCount')) 
      ) 
       innerQry.add(HRestrictions.eqProperty('part', 'outer.part') 

       // Using innerQuery, this criteria returns the parts having more than one team. 
       HDetachedCriteria outerQry = HDetachedCriteria.forClass(ZZPartAndTeam.class, 'outer') 
       outerQry.setProjection(Projections.projectionList() 
        .add(Projections.distinct(Projections.property('part').as('part'))) 
      ) 
       outerQry.add(Subqueries.gt(1, innerQry)) 

       builder.addToCriteria(Property.forName('part').in(outerQry)) 
      }