PSQLException: ERROR: current transaction is aborted, commands ignored until end of transaction bloc
这是个查询接口
场景:我在插入的时候如果遇到了唯一约束冲突,DuplicateKeyException,catch里面执行这个查询接口,查出来获取主键ID ,再通过主键ID去更改这条数据
//伪代码
try{
mapper.insertRecord(entity);
}catch(DuplicateKeyException e){
ReacorEntity existRecord = mapper.selectByDate(entity.getDate()); //这里查询报出事务被终止的错误
mapper.updateRecord(existRecord.getId(),entity);
}
这个查询接口单独调用时没有问题的,那么问题就出现在这使用场景里面。
想了很久,给师兄看了一下这个错误,他说这是行被锁。
瞬间反应过来,应该是我上面插入的时候遇到唯一约束冲突,然后这一行数据就锁住了,再查询的时候就会被强行终止。
解决方法,先查询存起来。
//伪代码
ReacorEntity existRecord = mapper.selectByDate(entity.getDate()); //放到插入前面
try{
mapper.insertRecord(entity);
}catch(DuplicateKeyException e){
if(existRecord != null){
mapper.updateRecord(existRecord.getId(),entity);
}
}
当然也可以在sql 语句里面写
//伪代码
insert into record(userId,"date",record_id) values(#{entity.userId},#{entity.date},#{entity.recordId})
on conflict(userId,"date") do update set record_id = #{entity.recordId}
这样就不用catch DuplicateKeyException 了。