我想使用条件对一些sql数据进行分组。让我们从看起来像这样的实体开始:
class CityEntity {
private String name;
private Date lastVisited;
}
我想要做的是找到所有城市并在转换器中返回结果:
class CityTransformer {
private String name;
private List<Date> lastVisited;
}
因此,您可以看到sql结果应按名称分组并将日期放入列表中。
我想使用标准这样做,所以它看起来几乎像这样:
Criteria criteria = session.createCriteria(CityEntity.class, "ce");
criteria.setProjection(Projections.projectionList().add(Projections.groupProperty("name"), "name"));
criteria.setResultTransformer(Transformers.aliasToBean(CityTransformer.class));
List<CityTransformer> cities = criteria.list();
问题在于我不知道如何将日期(lastVisited)汇总到列表中。有什么帮助吗?
例如,输入将如下所示(name,lastVisited):
[Los Angeles, 10-11-2014],
[Los Angeles, 11-12-2011],
[LosAngeles, 10-01-2011],
[Berlin, 01-10-2011]
并且输出应该如下所示
[LosAngeles, list[10-11-2014, 11-12-2011, 10-01-2011]],
[Berlin, list[01-10-2011]]
答案 0 :(得分:0)
您不需要SQL分组。您可以使用Java对其进行分组:
Criteria criteria = session.createCriteria(CityEntity.class, "ce");
criteria.setProjection(
Projections.projectionList()
.add( Projections.property("ce.name"), "ceName" )
.add( Projections.property("ce.lastVisited"), "ceLastVisited" )
);
List<Object[]> citiesAndDates = (List<Object[]>) criteria.list();
Map<String, CityTransformer> cityTransformerMap = new HashMap<String, CityTransformer>();
for(Object[] citiesAndDate : citiesAndDates) {
String city = (String) citiesAndDate[0];
Date date = (Date) citiesAndDate[1];
CityTransformer cityTransformer = cityTransformerMap.get(city);
if(cityTransformer == null) {
cityTransformer = new CityTransformer();
cityTransformerMap.put(city, cityTransformer);
}
cityTransformer.getLastVisited().add(date);
}
return cityTransformerMap;