Java Spring TransactionTemplate没有';不能处理异常
当我尝试捕获Java Spring TransactionTemplate没有';不能处理异常,java,spring,Java,Spring,当我尝试捕获DataIntegrityViolationException并将其转换为自定义异常时,不会执行catch块 作为示例,我使用了以下代码: 因此,ServicePointRepository抛出在我的控制器层处理的DataIntegrityViolationException,运行时代码似乎在避免捕获块 我做错了什么 这是PersistenceService中的代码: @Autowired private ServicePointRepository servicePointRep
DataIntegrityViolationException
并将其转换为自定义异常时,不会执行catch块
作为示例,我使用了以下代码:
因此,ServicePointRepository
抛出在我的控制器层处理的DataIntegrityViolationException
,运行时代码似乎在避免捕获块
我做错了什么
这是PersistenceService中的代码:
@Autowired
private ServicePointRepository servicePointRepository;
@Autowired
private BusinessExceptionFactory businessExceptionFactory;
@Autowired
private TransactionTemplate transactionTemplate;
@Override
public String save(final ServicePointDTO servicePointDTO) {
final ServicePointEntity servicePointEntity = mapToEntity(servicePointDTO);
return transactionTemplate.execute(status -> {
try {
return servicePointRepository.save(servicePointEntity).getId().toString();
} catch (DataIntegrityViolationException e) {
throw businessExceptionFactory.createBusinessException(AlreadyExistException.class, CommonError.ALREADY_EXIST);
}
});
}
这是正确的方法:
@Override
public String save(final ServicePointDTO servicePointDTO) {
final ServicePointEntity servicePointEntity = mapToEntity(servicePointDTO);
try {
return transactionTemplate.execute(status -> servicePointRepository.save(servicePointEntity).getId().toString());
} catch (DataIntegrityViolationException e) {
throw businessExceptionFactory.createBusinessException(AlreadyExistException.class, CommonError.ALREADY_EXIST);
}
}
此外,此方法不应标记为
@Transactional
您需要定义一个PersistenceExceptionTranslationPostProcessor后处理器,以使用将专有异常转换为Spring DataAccessException层次结构的逻辑代理存储库。还记得用@Repository注释标记存储库,以便检测和代理它们
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslatorPostProcessor(){
return new PersistenceExceptionTranslationPostProcessor();
}
或XML中的等效文件