Java 在唯一约束JPA/Hibernate期间添加自定义错误消息的更好方法
我认为在SpringBoot/hibernate中有更好的方法来实现这一点。有许多表,我不想为每个表添加用户定义的模型: 我有一个实体Java 在唯一约束JPA/Hibernate期间添加自定义错误消息的更好方法,java,spring,spring-boot,hibernate,jpa,Java,Spring,Spring Boot,Hibernate,Jpa,我认为在SpringBoot/hibernate中有更好的方法来实现这一点。有许多表,我不想为每个表添加用户定义的模型: 我有一个实体 @Entity public class Item extends ExtraEntity { @NotEmpty(message = "Item code can not be Empty !") @Column(unique = true) private String code;
@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);
}
}
}
@ExceptionHandler({ DuplicatedNameException.class })
public ResponseEntity<Object> handleDuplicatedNameException(Exception anException, WebRequest request) {
[...]
return new ResponseEntity<>(anException, new HttpHeaders(), YOUR_HTTP_STATUS_WITH_CUSTOM_CODE_HERE);
}
为每个唯一密钥创建自定义异常,如下所示:
public class DuplicatedNameException extends Exception {
public DuplicatedNameException(String message){
super(message);
}
public DuplicatedNameException(String message, Throwable anException){
super(message, anException);
}
}
定义从ResponseEntityExceptionHandler类扩展的异常处理程序,并按如下方式处理收到的异常:
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);
}
}
}
@ExceptionHandler({ DuplicatedNameException.class })
public ResponseEntity<Object> handleDuplicatedNameException(Exception anException, WebRequest request) {
[...]
return new ResponseEntity<>(anException, new HttpHeaders(), YOUR_HTTP_STATUS_WITH_CUSTOM_CODE_HERE);
}
@ExceptionHandler({DuplicatedNameException.class})
public ResponseEntity HandledReplicatedNameException(异常、WebRequest请求){
[...]
返回新的ResponseEntity(异常,新的HttpHeaders(),您的\u HTTP\u状态\u和这里的\u自定义\u代码\u);
}
此HTTPStatus是您应该在web层中检查的状态,以显示错误消息,如果您使用JPA,您需要实体,否则您不能使用JPA。