开发者

Hibernate Criteria API: count and group by with result in Map

The Car entity is mapped to a database table with 2 columns: ID and Color.

CarDao has the following method:

Map<Color, Integer> countByColor();

If we have 3 red cars and 2 blue cars in the database table, the method returns 开发者_C百科a map with 2 keys (red and blue) and the corresponding count (3 resp. 2).

I would like to do this with the Criteria API. What would the method look like? It’s the Map part that worries me.

Thanks.


I think what you are asking is not possible (without doing messy things) with the Criteria API : none of the method in the API returns a collection (that would be a map in your case), they only return Lists.

So what you could do is write your own ResultTransformer that would return a singleton list whose first and only element will be your map... but that would be a bit messy in my opinion.

something like that :

public class MyResultTransformer implements ResultTransformer {
    public Object transformTuple(Object[] tuple, String[] aliases) {
      return tuple;
    }
    public List transformList(List collection) {
      Map result = new LinkedHashMap(); // to preserve order
      // build the map from the collection
      ...
      return Collections.singletonList(result);
    }
}

to get tuples with only two elements (Color and count), use the Criteria.setProjections() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜