views:

266

answers:

1

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 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.

+1  A: 

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.

Thierry