[英]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.