使用 @controlleradvice 配合 @exceptionhandler 可以捕获 hibernate 抛出的 dataaccessexception 及其子类异常。在 spring boot 中,hibernate 的底层异常会被 persistenceexceptiontranslationpostprocessor 自动转换为 spring 的数据访问异常体系,因此只需在全局异常处理器中拦截 dataaccessexception 即可统一处理。

如何配置全局异常处理器来拦截数据访问异常
创建一个继承自 ResponseEntityExceptionHandler 或标注了 @RestControllerAdvice 的类,并在其中定义一个方法,使用 @ExceptionHandler(DataAccessException.class) 注解。该方法接收 DataAccessException 类型的参数,并返回自定义的响应体。这样,当 Hibernate 发生如主键冲突、约束违反等错误时,Spring 会自动将原始异常包装为 DataAccessException 的子类(如 DataIntegrityViolationException),从而被该处理器捕获。

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(DataAccessException.class)
public ResponseEntity<string> handleDataAccess(DataAccessException ex) {
if (ex instanceof DataIntegrityViolationException) {
return ResponseEntity.status(409).body("数据完整性错误:" + ex.getMessage());
}
return ResponseEntity.status(500).body("数据库操作失败:" + ex.getMessage());
}
}</string>
如何处理具体的 Hibernate 约束违反异常
在 DataAccessException 的处理逻辑中,进一步判断是否为 DataIntegrityViolationException。这是 Hibernate 在处理唯一约束、非空约束等违反情况时抛出的具体异常类型。通过检查异常实例,可以区分不同类型的数据库错误,例如主键重复或外键约束失败,并返回更精确的错误信息给前端。

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.dao.DataIntegrityViolationException;
import org.hibernate.exception.ConstraintViolationException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<string> handleConstraintViolation(DataIntegrityViolationException ex) {
Throwable cause = ex.getCause();
if (cause instanceof ConstraintViolationException) {
String msg = ((ConstraintViolationException) cause).getConstraintName();
return ResponseEntity.status(400).body("约束违反: " + msg);
}
return ResponseEntity.status(400).body("数据验证失败");
}
}</string>
当 Hibernate 会话关闭后执行查询会抛出什么异常
如果在事务提交后或会话关闭后尝试访问延迟加载的属性,Hibernate 会抛出 LazyInitializationException。这个异常同样属于 DataAccessException 体系,因此可以被同一个全局异常处理器捕获。在实际开发中,可以通过配置 OpenSessionInView 或在 DTO 转换阶段初始化数据来避免此问题,但捕获该异常是最后的兜底手段。











