【发布时间】:2020-08-09 11:52:27
【问题描述】:
我的代码如下所示:
@Transactional
public void save(Citizen citizen){
this.saveCitizen(citizen);
}
private void saveCitizen(Citizen citizen){
try{
citizenReposiory.save(citizen);
} catch(DataIntegrityViolationException exception){
//Exception on the line below
Citizen existingCitizen = citizenReposiory.findById(citizen.getId());
exisitingCitizen.setAge(50);
}
}
我首先试图拯救公民。如果抛出异常,那是因为该公民已经存在于数据库中。在这种情况下,我想改为更新现有行。但是,在上面的代码中,调用citizenReposiory.findById(citizen.getId()); 时会出现另一个异常。这是终端的sn-p:
[26-04-2020 00:35] WARN [o.h.engine.jdbc.spi.SqlExceptionHelper] - SQL Error: 1062, SQLState: 23000
[26-04-2020 00:35] ERROR [o.h.engine.jdbc.spi.SqlExceptionHelper] - Duplicate entry '10-2020-1' for key 'UKe4wgjj1wdqag5qhbcgnxhbvuj'
[26-04-2020 00:35] ERROR [org.hibernate.AssertionFailure] - HHH000099: an assertion failure occurred
(this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session):
org.hibernate.AssertionFailure: null id in dk.rsyd.mature.entities.WeeklyCare entry (don't flush the
Session after an exception occurs)
org.hibernate.AssertionFailure: null id in dk.rsyd.mature.entities.WeeklyCare entry (don't flush the
Session after an exception occurs)
这里发生了什么?捕获异常后是否无法继续事务?我尝试添加 @Transactional(noRollbackFor = DataIntegrityViolationException.class) 但这没有帮助。
【问题讨论】:
标签: java mysql spring transactions