我有一个JPA存储库方法,它应该保留一个对象列表
我的实体
@Query(value="select max(REALENERGY) as REALENERGY, `OBJECTID`, DATE_FORMAT(MAX(LASTUPDATE),'%Y-%m-%d %H:%i:00') "
+ "AS LASTUPDATE from ENERGY WHERE str_to_date(LASTUPDATE, '%Y-%m-%d %H:%i:%s' ) < " +
"str_to_date(:lastUpdate, '%Y-%m-%d %H:%i:%s' ) group by ROUND(UNIX_TIMESTAMP(LASTUPDATE) DIV 3600), OBJECTID"
+ " order by LASTUPDATE DESC", nativeQuery=true)
List<Object[]> historicizeEnergy(@Param("lastUpdate")String lastUpdate);
查询
@Override
public String saveEnergyHistory() throws ParseException {
LocalDateTime date = LocalDateTime.now().minusMinutes(15);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String lastUpdate = date.format(dtf);
List<Object[]> results = repository.historicizeEnergy(lastUpdate);
List<EnergyHistory> list = new ArrayList<>();
for(Object[] o : results){
EnergyHistory eh = new EnergyHistory();
eh.setRealEnergy((float) o[0]);
eh.setObject(objectService.findById((int) o[1]));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fromDate = sdf.parse((String) o[2]);
eh.setLastUpdate(fromDate);
list.add(eh);
}
repository.save(list);
return lastUpdate;
}
然后在我的服务类中我做
SQL Error: 1062, SQLState: 23000
Duplicate entry '5001574' for key 'PRIMARY'
但是当我调用save(list)时,它会保存列表中的一些元素,但在某个时刻它会因SQL错误而失败
1234
5678
778899
(显然重复的条目每次都会改变,它是一个预定的任务)。没有干净的原因,为什么添加一些行然后它失败..有时它增加3-400行,有时50 ...
修改
我也改变了,现在我保存每个对象而不是整个列表,但错误仍然存在...