Ken*_* H. 3 java validation annotations hibernate date
我们拥有现有的酒店管理系统。我被要求在系统的“创建住宿”功能中添加日期验证。该对话框如下所示:
如下面的代码所示,“结束日期”已经过验证。@FutureHibernate中的注释可确保日期在将来。
@NotNull
@Future
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date endDate;
编辑
我被要求在“开始日期”中添加验证。仅允许现在或将来的日期。我尝试使用@Present批注,但我想没有这种东西。不幸的是,@Future不接受今天的日期。我对这种事情是陌生的。所以我希望有人能帮助我。谢谢。
tha*_*guy 10
冬眠
您可以使用
@CreationTimestamp
@Temporal(TemporalType.DATE)
@Column(name = "create_date")
private Date startDate;
或更新
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modify_date")
private Date startDate;
Java(JPA)
您可以定义一个字段Date startDate;并使用
@PrePersist
protected void onCreateStartDate() {
startDate = new Date();
或更新
@PreUpdate
protected void onUpdateStartDate() {
startDate = new Date();
更新和示例
在更新问题以至于无法确定开始日期后,您必须采取其他方法。您需要编写一个自定义验证器来检查日期是现在还是将来,例如here。
因此,您可以在中引入新的注释PresentOrFuture.java:
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PresentOrFutureValidator.class)
@Documented
public @interface PresentOrFuture {
    String message() default "{PresentOrFuture.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
然后,您必须在中定义验证器PresentOrFutureValidator.java:
public class PresentOrFutureValidator
    implements ConstraintValidator<PresentOrFuture, Date> {
    public final void initialize(final PresentOrFuture annotation) {}
    public final boolean isValid(final Date value,
        final ConstraintValidatorContext context) {
        // Only use the date for comparison
        Calendar calendar = Calendar.getInstance(); 
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date today = calendar.getTime();
        // Your date must be after today or today (== not before today)
        return !value.before(today) || value.after(today);
    }
}
然后,您必须设置:
@NotNull
@PresentOrFuture
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date startDate;
好吧,这很详尽。我自己尚未进行测试,因为我现在没有设置可以进行测试,但是它应该可以工作。希望对您有所帮助。
现在,在更新的新验证器版本中,即
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.4.Final</version>
</dependency>
通过
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.0.Final</version>
</dependency>
我们有@FutureOrPresent和许多其他有用的注释,您可以使用它们。
| 归档时间: | 
 | 
| 查看次数: | 15308 次 | 
| 最近记录: |