Using sum and arithmetic result as order key in hibernate criteria

前端 未结 1 590
攒了一身酷
攒了一身酷 2021-01-16 20:54

How can I express this query in hibernate criteria.

SELECT anId, SUM(fieldA) AS A, SUM(fieldB) AS B, SUM(fieldA)+SUM(fieldB) AS \'total\' FROM tableA GROUP B         


        
相关标签:
1条回答
  • 2021-01-16 21:19

    following criteria should do the trick

            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);
            }
    
    0 讨论(0)
提交回复
热议问题