接收导致DataIntegrity违规的字段

时间:2018-06-28 14:41:46

标签: java spring exception

假设我有一个实体Person

public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false, unique=true)
    @Size(min=1,max=30)
    @NotEmpty
    private String name;
}

我想对约束违反等有例外。

name不能为空,并且大小必须在1到30个字符之间,

使用@Size@NotEmpty批注,我可以使用@Valid批注,例如

public ResponseEntity<?> addPerson(@Valid  @RequestBody  Person person)throws MethodArgumentNotValidException {

    }

但是,如果Name不是唯一的,该如何引发异常? 语音DataIntegrityViolationException

但是我想查找引发异常的列的名称和原因,例如“ name”和“ not unique”

有没有一种方法可以实现?使用DataIntegrityViolationException提供的一种方法需要对字符串进行大量解析:

@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<ValidationError> handleContraintExcepton(DataIntegrityViolationException ex){
    System.out.println(ex.getMostSpecificCause());
    System.out.println("=========");
    System.out.println(ex.getRootCause());
    System.out.println("===========");
    System.out.println(ex.getSuppressed());
    System.out.println("============");
    System.out.println(ex.getCause());
    System.out.println("============");
    ValidationError err = new ValidationError(ex.getLocalizedMessage(),ex.getMessage());
    return ResponseEntity.badRequest().body(err);
}

这两个方法都没有提供列名以及为什么会引发异常的原因

MethodArgumentNotValidException

我可以通过e.getField(), e.getCode()方法检索它。有没有办法用DataIntegrityViolationException实现它?

感谢帮助

0 个答案:

没有答案