Spring Data Rest - 处理实体验证

4

以下是代码:

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>{
}

现在,当我将null发送到name属性时,验证器会正确验证,但实际抛出的异常是TransactionRollbackException。
就像这样。
{
    "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异常。我在日志中看到了异常,但它没有被抛出。

2个回答

1
这是因为Spring的TransactionInterceptor覆盖了你的异常。
根据Spring的文档,实现存储库实体验证的惯用方法是使用Spring Data Rest Events。你可能想使用BeforeSaveEventBeforeCreateEvent
你可以为实体创建自定义类型安全处理程序(有关详细信息,请参见提供的链接),其类似于:
@RepositoryEventHandler 
public class PersonEventHandler {

  @HandleBeforeSave
  public void handlePersonSave(Person p) {
    // … you can now deal with Person in a type-safe way
  }
}

另一种方法是注册一个仓库监听器,它扩展了AbstractRepositoryEventListener,文档中也有描述。

谢谢。但我正在寻找通用的东西。上面的答案解决了它。 - madhairsilence

1

当配置RepositoryRestConfigurerAdapter时,您可以将LocalValidatorFactoryBean添加到ValidatingRepositoryEventListener中,如下所示:

@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);
    }
}

使用处理程序是一种更方便的方式,因为它可以让您以类型安全的方式使用对象(例如 Person,而不是 Object - 这是在使用 Validator 时的情况)。 - hovanessyan
@hovanessyan 这个问题是关于“如何获取ConstraintViolation”,而不是关于“如何验证我的实体”的... - Cepr0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接