1、自定义实体
/**
-
Created by administor on 2018-7-18 17:50.
*/
public class CarTraceResult {
private String plateNo;
private Integer plateColor;
private String typeName;
private String parkName;
private Calendar time;
private Long times;public CarTraceResult(String plateNo, Integer plateColor, String typeName, String parkName, Calendar time, Long times) {
this.plateNo = plateNo;
this.plateColor = plateColor;
this.typeName = typeName;
this.parkName = parkName;
this.time = time;
this.times = times;
}//省略get、set方法
}
CarTraceResult需要实现构造方法,因为后面会用到。
2、查询@Query(value = "select new com.park.carTrace.pojo.CarTraceResult(a.plateNo, a.plateColor, a.typeName, a.parkName, max(a.time) as time, count(a.id) as times) " +
" from CarTraceRecordEntity a where a.plateNo = ?1 and a.plateColor = ?2 " +
"and a.type = ?3 group by a.parkNo order by time desc ")
List queryCarTraceRecord(String plateNo, Integer plateColor, Integer type);
网友有强调自定义实体类的属性和名称要与查询结果完全对应,那么问题来了,由于我使用了max()和count()函数,并分别将对应结果起了别名,该语句在执行中是报错的。到这里,似乎是无解了。反复尝试后,大胆将代码改为:
@Query(value = "select new com.park.carTrace.pojo.CarTraceResult(a.plateNo, a.plateColor, a.typeName, a.parkName, max(a.time), count(a.id)) " +
" from CarTraceRecordEntity a where a.plateNo = ?1 and a.plateColor = ?2 " +
"and a.type = ?3 group by a.parkNo order by time desc ")
List queryCarTraceRecord(String plateNo, Integer plateColor, Integer type);