【发布时间】:2020-03-28 05:21:41
【问题描述】:
我有两个不同的服务:第一个是保存一个对象到数据库,第二个是更新现有的对象。
我正在为我的对象使用验证约束,例如(@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);
}
}
【问题讨论】:
-
我也在这里检查了这个解决方案,stackoverflow.com/questions/29798346/… 但我认为它可能已经过时并且可能有更好的解决方案。
标签: java spring spring-boot validation