对托管实体的Bean验证

时间:2014-10-30 09:11:06

标签: java hibernate bean-validation hibernate-validator

在休息ubdate请求中,首先我从数据库读取相关对象,第二个映射dto到使用dozer framework standart mapper,DozerBeanMapper重新引导的dbObject。接下来,我正在尝试验证新的映射对象,但验证失败,因为有一个注释的字段 @NotEmpty(message = "Name cannot be empty ") 似乎是null,我知道这是因为dbObject是一个动态代理对象引用我的hibernate处理的实体,有没有办法用hibernate验证使用hibernate.validator.constaints注释的托管bean验证者。

@PUT
public Response update(QueryDTO dto) throws   ServiceException {
    log.info("Request for upadating   query");

     Query dbObject= this.persistenceService.find( Query.class,dto.getSystemId());
     if(dbObject.getVersion()!=dto.getVersion()){
          throw new InvalidVersionException("Db version is" + dbObject.getVersion());
     }
    this.mapper.map(dto,dbObject);


    Set<ConstraintViolation<Query>>  validationResult= this.validator.validate(dbObject);
    if(!validationResult.isEmpty()){
        throw new ValidationException(StringifyUtil.buildExceptionMessage(validationResult));
    }

    Query updatedObject=   this.persistenceService.update(dbObject);
    return ok(updatedObject);
}

1 个答案:

答案 0 :(得分:1)

在BeanValidation API中,TraversableResolver用于检查验证程序是否可以访问该属性。根据你正在使用的hibernate验证器版本,Hibernate / JPA的实现解决了这个问题。

http://docs.oracle.com/javaee/7/api/javax/validation/TraversableResolver.html https://docs.jboss.org/hibernate/validator/5.0/api/org/hibernate/validator/internal/engine/resolver/package-summary.html

您可以这样配置TraversableResolver

    final Configuration<?> conf = Validation.byDefaultProvider().configure();
    conf.traversableResolver(new MyTraversableResolver());
    ValidatorFactory validatorFactory = conf.buildValidatorFactory();

请参阅https://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/chapter-bootstrapping.html#d0e4238以了解引导验证程序