Spring data rest - 处理实体验证

Spring data rest - Handle entity validation

这是代码

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 时,验证器会正确验证它,但抛出的实际异常是 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 异常。我确实在日志中看到异常。但是它没有被抛出。

原因是 Spring 的 TransactionInterceptor 覆盖了您的异常。

根据 Spring's documentation, is to use Spring Data Rest Events. You probably want to use BeforeSaveEvent or BeforeCreateEvent.

实现存储库实体验证的惯用方式

您可以为实体创建自定义 type-safe 处理程序(有关详细信息,请参阅提供的 link),它看起来类似于:

@RepositoryEventHandler 
public class PersonEventHandler {

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

另一种方法是注册一个扩展 AbstractRepositoryEventListener 的 Repository Listener,文档中也有描述。

您可以添加 LocalValidatorFactoryBean to ValidatingRepositoryEventListener when configuring 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);
    }
}