无法捕获 DataIntegrityViolationException

kkf*_*flf 1 spring hibernate jpa spring-boot

我将 Spring Boot 2 与 spring-boot-starter-data-jpa 与底层 MariaDB 一起使用。

我有一个带有唯一键“用户名”的表。我想DataIntegrityViolationException知道是否违反了这个约束,但似乎 Spring 正在记录DataIntegrityViolationException并且不会重新抛出 after logging(我最好的猜测)。MySQLIntegrityConstraintViolationException而是抛出。

我想赶DataIntegrityViolationExceptionUserService.createUser(..)

下面是几个代码片段:

@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);
}
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:

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'
...
Run Code Online (Sandbox Code Playgroud)

kkf*_*flf 5

我解决了这个问题。

在事务提交之前不会发生异常,这是完全有道理的。

我能够在控制器类中捕获事务范围之外的异常。