gpt4 book ai didi

java - Hibernate 验证注解——验证至少一个字段不为空

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:34 26 4
gpt4 key购买 nike

有没有一种方法可以使用定义的注解来定义 Hibernate 验证规则 here , 声明至少一个字段不应为空?

这将是一个假设的例子(@OneFieldMustBeNotNullConstraint 并不真正存在):

@Entity
@OneFieldMustBeNotNullConstraint(list={fieldA,fieldB})
public class Card {

@Id
@GeneratedValue
private Integer card_id;

@Column(nullable = true)
private Long fieldA;

@Column(nullable = true)
private Long fieldB;

}

在图示的情况下,fieldA 可以为 null 或 fieldB 可以为 null,但不能同时为 null。

一种方法是创建我自己的 validator ,但如果它已经存在我想避免。如果您已经制作了一个 validator ,请分享一个 validator ...谢谢!

最佳答案

我终于写出了整个 validator :

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;

import org.apache.commons.beanutils.PropertyUtils;

@Target( { TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckAtLeastOneNotNull.CheckAtLeastOneNotNullValidator.class)
@Documented
public @interface CheckAtLeastOneNotNull {

String message() default "{com.xxx.constraints.checkatleastnotnull}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

String[] fieldNames();

public static class CheckAtLeastOneNotNullValidator implements ConstraintValidator<CheckAtLeastOneNotNull, Object> {

private String[] fieldNames;

public void initialize(CheckAtLeastOneNotNull constraintAnnotation) {
this.fieldNames = constraintAnnotation.fieldNames();
}

public boolean isValid(Object object, ConstraintValidatorContext constraintContext) {

if (object == null) {
return true;
}
try {
for (String fieldName:fieldNames){
Object property = PropertyUtils.getProperty(object, fieldName);

if (property != null) return true;
}
return false;
} catch (Exception e) {
return false;
}
}
}
}

使用示例:

@Entity
@CheckAtLeastOneNotNull(fieldNames={"fieldA","fieldB"})
public class Reward {

@Id
@GeneratedValue
private Integer id;

private Integer fieldA;
private Integer fieldB;

[...] // accessors, other fields, etc.
}

关于java - Hibernate 验证注解——验证至少一个字段不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12211734/

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