2013-04-18 31 views
1

我必須在實體干預的字段「heureFin」&「heureDebut」上設置一個約束條件,我不知道如何精確限制這個約束:heureFin> heureDebut ?? 這裏是我的實體:在實體中指定表示日期的字段上的約束條件JPA

public class Intervention implements Serializable { 
    private static final long serialVersionUID = 1L; 
    @Id 
    @Size(min = 1, max = 50) 
    @Column(name = "IdIntervention", length = 50) 
    private String idIntervention; 
    @Basic(optional = false) 
    @NotNull 
    @Column(name = "HeureDebut", nullable = false) 
    @Temporal(TemporalType.TIMESTAMP) 
    private Date heureDebut; 
    @Basic(optional = false) 
    @NotNull 
    @Column(name = "HeureFin", nullable = false) 
    @Temporal(TemporalType.TIMESTAMP) 
    private Date heureFin; 
} 

是否有可能,還是應該在其他地方處理這個約束?

先謝謝您:)

回答

1

這是不可能在會員級別。您應該使用類級約束並實現您自己的約束驗證程序(將實例用作其isValid()方法的參數,以方便比較)。

創建自定義的驗證:

public class HourRangeValidator implements Constraint<InterventionHourRange, Intervention> { 

和實施isValid法所需要的比較邏輯。

創建自定義註釋:

@ConstraintValidator(HourRangeValidator.class) 
@Target(TYPE) 
@Retention(RUNTIME) 
public @interface InterventionHourRange { 
    String message() default "{your.error.message}"; 
    String[] groups() default {}; 
} 

而且annote你的實體:

@InterventionHourRange 
public class Intervention implements Serializable { 

http://docs.jboss.org/hibernate/validator/4.0.1/reference/en/html/validator-customconstraints.html

+0

感謝您對尼古拉幫助:) – mounaim