[英]Bean validation Java conditional
现在我有一个BaseSchedule
类,它由4个类(组成)使用。 我想在两个使用类而不是在其他使用类中进行验证。 我对如何操作有些困惑。
我的BaseSchedule
如下所示:
@Embeddable
@DatesStartBeforeEnd(start = "startDateTime", end = "endDateTime")
public class BaseSchedule implements Serializable {
private Date startDateTime;
private Date endDateTime;
}
我要检查以确保将数据持久保存到数据库时startDateTime
和endDateTime
不为null。 通常我会为每个字段提供一个@NotNull
。
public class TimeSlot implements Scheduleable {
@Embedded
private BaseSchedule schedule;
}
但是...就我的TimeSlotTemplate
而言,我不希望验证,因为我知道它将为null。
public class TimeSlotTemplate extends SchedulableClassTemplateEvent {
@Embedded
private BaseSchedule schedule;
}
如果您将Hibernate Validator用作BV提供程序,则一种解决方案可能是使用自定义默认组序列提供程序 。
为此,您的BaseSchedule
对象必须知道其当前具有的“角色”,例如,将带有SlotSchedule
, TemplateSchedule
SlotSchedule
的枚举传递给其构造函数。 如果角色是TemplateSchedule
则根据角色的作用,组序列提供程序可以确定要验证的序列,并返回不包含@NotNull
约束的序列。
并不是说这种方法要求您在JPA生命周期验证期间使用默认序列。
我认为可以使用@PrePersist注释来完成。
@PrePersist
public void prePersist(){
if(isPerformNullableCheck()){
// check for null values and raise an error if invalid
}
}
在您的TimeSlotTemplate中,您可以将performNullableCheck属性设置为false。
另一种方法可能是将一个类添加到层次结构中。 BaseSchedule包含所需的属性,例如ValidatedSchedule(扩展BaseSchedule)将覆盖这些属性并执行notnull检查。 不知道这是否有效。 同样,这可能不是解决您问题的最佳解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.