javax.validation.Validator排除一些字段

时间:2019-12-03 13:45:58

标签: java spring spring-boot validation

我有两种不同的服务:第一种是将对象保存到数据库中,第二种是用于更新现有对象。

我正在为我的对象使用验证约束,例如(@ NotBlank,@ Size,@ Pattern等),在第一种情况下,我需要验证对象的所有字段,但在后一种情况下,某些字段需要从验证器中排除。

当前,我正在使用javax.validation.Validator进行验证。这是我的对象...

public class Person {

  private Long id;

  @NotBlank
  @Size(max = 45)
  private String name;

  @Size(max = 5000)
  private String description;

  @Size(max = 300)
  private String address;
}

...,我想在更新验证期间排除“地址”字段。

@Named
@RequiredArgsConstructor
@Service
@Slf4j
public class PersonService {

private final PersonRepository repository;
private final Validator validator = buildDefaultValidatorFactory().getValidator();

public Person save(Person person) {
    Set<ConstraintViolation<Person>> violations = validator.validate(person);

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(new HashSet<>(violations));
    }

    return repository.save(person);
}

public Person update(Person person) {
    Set<ConstraintViolation<Person>> violations = validator.validate(person); //exclude address field here

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(new HashSet<>(violations));
    }

    return repository.save(person);
}
}

1 个答案:

答案 0 :(得分:0)

如果需要排除地址属性,只需在验证之前将其设置为null。并将其设置为验证后的先前值:

public Person update(Person person) {
    String address = person.getAddress();
    person.setAddress(null);

    Set<ConstraintViolation<JobAd>> violations = validator.validate(person);

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(new HashSet<>(violations));
    }

    person.setAddress(address)
    return repository.save(person);
}