在唯一约束JPA /休眠期间添加自定义错误消息的更好方法

问题描述

我认为在Spring Boot / Hibernate中有一种更好的方法。有很多表,我不想为每个表添加用户定义”模型:here

我有一个实体

@Entity
public class Item extends ExtraEntity {
       @NotEmpty(message = "Item code can not be Empty !")
       @Column(unique = true)
       private String code;
       @NotEmpty (message = "Item name can not be Empty !")
       @Column(unique = true)
       private String name;
}

如何为我的REST API发送自定义消息,说明代码重复还是名称重复?

解决方法

在最外层,捕获异常,如下所示:

try {
    newEntity = ourService.createUpdate(entity);
} catch (JpaSystemException jpae) {
    if (jpae.getCause().getCause() instanceof ConstraintViolationException) {
        if (((ConstraintViolationException)jpae.getCause().getCause()).getConstraintName().equals("SCHEMA.UK_CODE_01")){
            throw new DuplicatedCodeException("Message",jpae);
        } else if (((ConstraintViolationException)jpae.getCause().getCause()).getConstraintName().equals("SCHEMA.UK_NAME_01")){
            throw new DuplicatedNameException("Message",jpae);
        }
    }
}

为每个唯一键创建一个自定义异常,如下所示:

public class DuplicatedNameException extends Exception {

    public DuplicatedNameException(String message){
        super(message);
    }

    public DuplicatedNameException(String message,Throwable anException){
        super(message,anException);
    }
}

定义一个从ResponseEntityExceptionHandler类扩展的异常处理程序,并对接收到的异常进行如下处理:

@ExceptionHandler({ DuplicatedNameException.class })
    public ResponseEntity<Object> handleDuplicatedNameException(Exception anException,WebRequest request) {

    [...]

    return new ResponseEntity<>(anException,new HttpHeaders(),YOUR_HTTP_STATUS_WITH_CUSTOM_CODE_HERE);
}

此HTTPStatus是您应该在Web层中检查以显示错误消息的一个状态