Hibernate Criteria Group by AND Order By

时间:2016-09-14 18:13:13

标签: java hibernate criteria

我需要将下一个查询放入条件

SELECT DISTINCT SUBSTRING(id, 1, LENGTH(id)-3) AS id_trunc, MAX(version) as version, MAX(code) as code
FROM theTable 
WHERE (version like '%.%' AND NOT version LIKE '%.0' AND event_code LIKE 'CODE1') OR (version LIKE '%.0' AND code LIKE 'CODE2')
GROUP BY id_trunc
ORDER BY id_trunc, version, code

我有使用Criteria的经验,但仅仅是为了简单的东西,在这种情况下,我需要一种方法来进行投影,分组依据和订单依据。我试过几次,但我无法使它工作。我到处寻找,但我找不到任何像这个一样复杂的查询帮助。

这就是我现在所拥有的

    Criterion whereClause = Restrictions.and(Restrictions.like("version","%.%"), 
                            Restrictions.and(Restrictions.not(Restrictions.like("version","%.0")),Restrictions.like("code","CODE1")));

    Criterion secondWhere = Restrictions.and(Restrictions.like("Version","%.0"), Restrictions.like("code","CODE2"));
    LogicalExpression orWhere= Restrictions.or(whereClause,secondWhere);
    criteria.add(orWhere);

1 个答案:

答案 0 :(得分:0)

你有限制部分。

所以,计算你的预测:

        var data = [    
            {text: "hello"},
            {text: "good bye"},
            {text: "Hello again"}       
        ]

        $.each( data, function( key, value ) {
            console.log( value.text );
        });

现在要映射你的结果,你需要另一个对象,它只包含三个字段和一个变换器。

criteria.setProjection(Projections.projectionList().
  add(Projections.groupProperty("SUBSTRING(id, 1, LENGTH(id)-3)", "id_trunc")).
  add(Projections.max("version")).
  add(Projections.max("code")))  

对于ORDER BY:

 criteria.setResultTransformer(Transformers.aliasToBean(TruncatedIdWithMaxVersion.class))