Criteria分组查询,拿到的结果集中只有id,recordDate,device_id三个值:
Criteria crit = deviceRecordDao.getSession().createCriteria(DeviceRecord.class);
ProjectionList proList = Projections.projectionList();
crit.setFetchMode("device", FetchMode.JOIN);
crit.setFetchMode("deviceRecord", FetchMode.JOIN);
crit.createAlias("device", "device");
crit.createAlias("device.office", "office");
crit.add(dataScopeFilter(user, "office", "", true));
crit.add(Restrictions.eq(DeviceRecord.FIELD_DEL_FLAG, DeviceRecord.DEL_FLAG_NORMAL));
crit.add(Restrictions.eq("device.delFlag", DeviceRecord.DEL_FLAG_NORMAL));
crit.addOrder(Order.desc("recordDate"));
proList.add(Projections.id());
proList.add(Projections.max("recordDate"));
proList.add(Projections.groupProperty("device.id"));
crit.setProjection(proList);
List results = crit.list();
results返回的是一个Object类型,要把它转换成相应的实体类:
List<DeviceRecord> topicList2 = Lists.newArrayList();
for(int i=0;i<results.size();i++){
DeviceRecord dr = new DeviceRecord();
Object[] obj = (Object[]) results.get(i);
dr.setId(obj[0].toString());
topicList2.add(dr);
}
return topicList2;
完成