现在我有一个类BaseSchedule
它被4个类(组合)使用。我想在两个使用类中进行验证,而不是在其他类中进行验证。我有点不知道如何做到这一点。
我的BaseSchedule
如下所示:
@Embeddable
@DatesStartBeforeEnd(start = "startDateTime", end = "endDateTime")
public class BaseSchedule implements Serializable {
private Date startDateTime;
private Date endDateTime;
}
当我将数据保存到数据库时,我想检查以确保 startDateTime
和 endDateTime
不为空。通常我会为每个字段提供一个@NotNull
。
public class TimeSlot implements Scheduleable {
@Embedded
private BaseSchedule schedule;
}
但是...就我的 TimeSlotTemplate
而言,我不需要验证,因为我知道它将为空。
public class TimeSlotTemplate extends SchedulableClassTemplateEvent {
@Embedded
private BaseSchedule schedule;
}
最佳答案
如果您使用 Hibernate Validator 作为 BV 提供程序,一种解决方案可能是使用自定义 default group sequence provider .
要实现此功能,您的 BaseSchedule
对象必须了解它当前具有的“角色”,例如通过将带有诸如 SlotSchedule
、TemplateSchedule
等值的枚举传递给其构造函数。根据角色,组序列提供程序可以确定要验证的序列,并返回不包含 @NotNull
约束的序列(如果角色是 TemplateSchedule
)。
并不是说此方法要求您在 JPA 生命周期验证期间使用默认序列。
关于java - Java 条件 Bean 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19434919/