gpt4 book ai didi

java - Spring data rest - 处理实体验证

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:08:56 24 4
gpt4 key购买 nike

这是代码

Person.java

@Entity
class Person {
@Id private Long Id;
@NotNull private String name;
//getter setters
}

PersonRepository.java

@RepositoryRestResource(collectionResourceRel = "person", path="person" )
interface PersonRepository extends CrudRepository<Person,Long>{
}

现在,当我针对 name 属性发送 null 时, validator 会正确验证它,但抛出的实际异常是 TransactionRollbackExecption。

像这样

{
"timestamp": "2018-03-14T09:01:08.533+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction",
"path": "/peron"
}

如何获得实际的 ConstraintViolation 异常。我确实在日志中看到异常。但它不会被抛出。

最佳答案

您可以添加 LocalValidatorFactoryBeanValidatingRepositoryEventListener配置时 RepositoryRestConfigurerAdapter ,像这样:

@Configuration
public class RepoRestConfig extends RepositoryRestConfigurerAdapter {

private final LocalValidatorFactoryBean beanValidator;

public RepoRestConfig(LocalValidatorFactoryBean beanValidator) {
this.beanValidator = beanValidator;
}

@Override
public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener v) {
v.addValidator("beforeCreate", beanValidator);
v.addValidator("beforeSave", beanValidator);
super.configureValidatingRepositoryEventListener(v);
}
}

关于java - Spring data rest - 处理实体验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49273431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com