我通过以下设置获得了一个启用SpringBoot的应用:
@Configuration
类使用@EnableTransactionManagement
TransactionManager定义在@Configuration
类的某个地方:
@Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager();
}
@Controller类:
@RequestMapping(method = RequestMethod.DELETE, value = "/{entityId}")
@Transactional(noRollbackFor = DataIntegrityViolationException.class)
public ResponseEntity<DeleteEntityResponse> deleteEntity(@PathVariable @NotNull long entityId) {
T existing = getRepository().findOne(entityId);
try {
repository.delete(existing);
repository.flush();
deleteEntityResponse.setDeleted(true);
} catch (final DataIntegrityViolationException ex) {
entityManager.detach(existing);
deleteEntityResponse.setErrorMessage("general.error.delete.DataIntegrityViolationException");
}
return new ResponseEntity<>(deleteEntityResponse,
deleteEntityResponse.isDeleted()
? HttpStatus.OK
: HttpStatus.METHOD_NOT_ALLOWED);
}
稍后在同一个Controller类中,我定义了异常处理方法:
@ExceptionHandler
public ResponseEntity<ErrorResponse> handleAllSortsOfExceptions(Exception exception) {
}
我期待当我尝试删除实体并且操作因DataIntegrityViolationException而失败时,我将返回ResponseEntity<DeleteEntityResponse>
,但我会回来ResponseEntity<ErrorResponse>
。
ResponseEntity<ErrorResponse>
。这是用org.springframework.transaction.TransactionSystemException调用的:无法提交JPA事务;嵌套异常是javax.persistence.RollbackException:事务标记为rollbackOnly。
我的问题是 - 如何配置事务管理以便它理解@Transactional注释?