无法捕获DataIntegrityViolationException [英] Cannot catch DataIntegrityViolationException
问题描述
我正在将Spring Boot 2与带有基础MariaDB的spring-boot-starter-data-jpa一起使用.
I am using Spring Boot 2 with spring-boot-starter-data-jpa with an underlying MariaDB.
我有一个带有唯一键用户名"的表.如果违反了此约束,我想捕获 DataIntegrityViolationException
,但似乎Spring正在记录 DataIntegrityViolationException
,并且在记录后不重新抛出(我的最佳猜测).会引发 MySQLIntegrityConstraintViolationException
.
I have table with a unique key "username". I want to catch DataIntegrityViolationException
if this constraint is violated, but it seems like Spring is logging DataIntegrityViolationException
and does not rethrow the after logging(my best guess). MySQLIntegrityConstraintViolationException
is thrown instead.
我想在 UserService.createUser(..)
中捕获 DataIntegrityViolationException
.
以下是一些代码段:
@Repository
@Transactional(propagation = Propagation.MANDATORY)
public class UserRepository {
@PersistenceContext
private EntityManager entityManager;
public void save(User user) {
entityManager.persist(user);
}
}
@Service
@Transactional(value = Transactional.TxType.REQUIRED)
public class UserService {
@Autowired
private UserRepository userRepository;
private void createUser(User user){
userRepository.save(user);
}
Stacktrace:
Stacktrace:
2018-09-22 14:20:33.163 WARN 10700 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1062, SQLState: 23000
2018-09-22 14:20:33.163 ERROR 10700 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry 'kkflf' for key 'user_username_uindex'
2018-09-22 14:20:33.163 ERROR 10700 --- [nio-8080-exec-1] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2018-09-22 14:20:33.177 ERROR 10700 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [user_username_uindex]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'kkflf' for key 'user_username_uindex'
...
推荐答案
我解决了这个问题.
在事务提交之前不会发生异常,这是很合理的.
The exception does not occur until the transaction commits, which makes perfect sense.
我能够在控制器类的事务范围之外捕获异常.
I was able to catch the exception outside the transaction scope in a controller class.
这篇关于无法捕获DataIntegrityViolationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!