使用sum和算术结果作为hibernate准则中的顺序键

时间:2014-02-20 05:26:50

标签: hibernate java-ee criteria hibernate-criteria

如何在休眠标准中表达此查询。

SELECT anId, SUM(fieldA) AS A, SUM(fieldB) AS B, SUM(fieldA)+SUM(fieldB) AS 'total' FROM tableA GROUP BY anId ORDER BY 'total' DESC LIMIT 5

1 个答案:

答案 0 :(得分:4)

以下标准应该可以解决问题

        Criteria criteria = hibernateSession
                .createCriteria(YourEntity.class);
        criteria.setProjection(Projections
                .projectionList()
                .add(Projections.property("anId").as("prop1"))
                .add(Projections.sum("fieldA").as("prop2"))
                .add(Projections.sum("fieldB").as("prop3"))
                .add(Projections.sqlProjection(
                        "sum(fieldA) + sum(fieldB) as total",
                        new String[] { "total" },
                        new Type[] { StandardBasicTypes.INTEGER }), "total")
                .add(Projections.groupProperty("remarks")));
        criteria.addOrder(Order.desc("total"));
        criteria.setMaxResults(5);
        criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List list = criteria.list();
        for (Object object : list) {
            Map<Object, Object> map = (Map<Object, Object>) object;
            System.out.println(map);
        }