gpt4 book ai didi

javax.validation.Validator 排除某些字段

转载 作者:行者123 更新时间:2023-12-01 19:42:43 33 4
gpt4 key购买 nike

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

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

目前,我正在使用 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);
}
}

最佳答案

如果需要排除地址属性,只需在验证之前将其设置为 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);
}

关于javax.validation.Validator 排除某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59158528/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com