如何在 Spring Boot 中捕获 hibernate/jpa 约束违规?

海伦·里夫斯

我一直无法在 ResponseEntityExceptionHandler 中捕获 ConstraintViolationException(或 DataIntegrityViolationException)。我想在响应中返回 jpa 失败(例如违反了哪个约束)。(我不喜欢在方法参数上使用 @Valid 并捕获 handleMethodArgumentNotValid )。

...
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataIntegrityViolationException;

@ControllerAdvice
public class PstExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler({ConstraintViolationException.class})
    public ResponseEntity<Object> handleConstraintViolation(
        ConstraintViolationException ex, WebRequest request) {

        ...

        return new ResponseEntity<Object>(...);
    }
}

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
public class Student {

    @Id
    private Long id;

    @NotNull
    private String name;

    @NotNull
    @Size(min=7, message="Passport should have at least 7 characters")
    private String passportNumber;

    public Student() {
    }

...

}

@RequestMapping(value = "/addstudent"...)
@ResponseBody
public ResponseEntity<Object> addStudent(@RequestBody StudentDto studentDto) {

    Student student = new Student();
    student.setId(studentDto.getId());                          // 1L
    student.setName(studentDto.getName());                      // "helen"
    student.setPassportNumber(studentDto.getPassportNumber());  // "321"

    studentRepository.save(student);

    return ResponseEntity.accepted().body(student);
}

谢谢你...

狂野开发者

有3种方式:

  1. @Valid\@Validated注释。

    一旦它们在参数级别使用,就可以通过方法注入的Errors\BindingResult类型实现来获得违规

  2. ConstraintViolationException每次将处于无效状态的实体传递给.save().persist()Hibernate 方法时都会抛出

  3. 实体可以通过注入LocalValidatorFactoryBean.validate()方法手动验证然后通过传递的Errors对象的实现可以使用约束违规确切地说,@Valid\@Validated注释是如何在内部实现的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Spring Boot中捕获非MVC和非REST异常

如何在Spring Boot中禁用ErrorPageFilter?

如何在Spring Boot中以Spring Security级别启用CORS

我如何捕获通过POST来执行Spring Boot中存储的过程的值

如何在Spring Boot中从sagger中删除Authentication参数?

尝试删除记录时,如何在Spring-Boot中修复“违反外键约束”。使用@ManyToMany

在Spring Boot的OneToMany关系中如何解决“无法执行语句; SQL [n / a];约束[null]”

如何在Spring Boot中获取请求的URL

如何在Spring Boot中配置SSL?

在Spring Boot中,如何在显示error.html之前捕获错误并对其进行处理?

如何在Spring Boot中访问JMS统计信息?

如何在Spring Boot中调试请求?

如何在Spring Boot中从原始查询中获取数据?

如何在Spring Boot中关闭调试日志消息

如何在Spring Boot中捕获错误请求

如何在Spring Boot中覆盖Spring Security默认配置

如何在Spring Boot中处理DeferredResult中的异常?

如何在Spring Boot REST API中捕获AccessDeniedException

我如何在Spring Boot中在DatabaseConfig中设置属性

Spring Boot:如何在Spring Boot应用程序中显示系统目录中的图像?

如何在Spring Boot异步功能中处理未捕获的异常?

唯一约束违反了oracle错误。如何在python中获取违规的插入语句?

如何在Spring Boot中替换Spring ApplicationContext

Hibernate-如何捕获“完整性约束违规:唯一约束或索引违规”

如何在spring boot中查询关系?

如何在 Spring Boot 中修复 RestTemplate NullPointerException?

如何在 Spring Boot 中为 @Cacheable 设置过期时间?

如何在 Spring Boot 中按方法参数缓存?

如何在约束违规列表中展开、提取、约束违规异常?