java 使用 Hibernate 验证日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40482252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:15:13  来源:igfitidea点击:

Validation of a date with Hibernate

javahibernatevalidationdateannotations

提问by Kendall H.

We have an existing hotel management system. I was asked to add a date validation in the "Create Accommodation" function in the system. The dialog looks like this:

我们有一个现有的酒店管理系统。我被要求在系统的“创建住宿”功能中添加日期验证。该对话框如下所示:

enter image description here

在此处输入图片说明

The "End Date" is already validated as shown in the code below. The @Futureannotation in Hibernate ensures that the date is in the future.

“结束日期”已经过验证,如下面的代码所示。@FutureHibernate 中的注解确保日期在未来。

@NotNull
@Future
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date endDate;

EDIT

编辑

I was asked to add a validation to the "Start date". Only the present or a future date is allowed. I tried to use a @Presentannotation, but I guess there is no such thing. Unfortunately, @Futuredoes not accept today's date. I am new to this kind of thing. So I hope someone can help me. Thank you.

我被要求向“开始日期”添加验证。只允许现在或将来的日期。我尝试使用@Present注释,但我想没有这样的东西。不幸的是,@Future不接受今天的日期。我对这种事情很陌生。所以我希望有人可以帮助我。谢谢你。

回答by thatguy

Hibernate

休眠

You can use

您可以使用

@CreationTimestamp
@Temporal(TemporalType.DATE)
@Column(name = "create_date")
private Date startDate;

or on update

或在更新

@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modify_date")
private Date startDate;

Java (JPA)

爪哇 (JPA)

You can define a field Date startDate;and use

您可以定义一个字段Date startDate;并使用

@PrePersist
protected void onCreateStartDate() {
startDate = new Date();

or on update

或在更新

@PreUpdate
protected void onUpdateStartDate() {
startDate = new Date();

Update and example

更新和示例

After you have updated your question to not fix the start date to the present, you have to do a different approach. You need to write a custom validator to check if a date is now or in the future, like here.

在您更新问题以不将开始日期固定为当前之后,您必须采用不同的方法。您需要编写一个自定义验证器来检查日期是现在还是将来,就像这里

Therefore you can introduce a new annotation in PresentOrFuture.java:

因此,您可以在 中引入新的注释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 {};
}

Then you have to define the validator in PresentOrFutureValidator.java:

然后你必须定义验证器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);

    }
}

Then you have to set:

然后你必须设置:

@NotNull
@PresentOrFuture
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date startDate;

Well, that was exhausive. I have not tested it myself, since I do not have a set-up to do so now, but it should work. I hope it helps.

嗯,那是详尽无遗的。我自己没有测试过,因为我现在没有这样做的设置,但它应该可以工作。我希望它有帮助。

回答by Ankit Bhatnagar

Now, in the updated new validator version i.e.

现在,在更新的新验证器版本中,即

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.4.Final</version>
</dependency>

via

通过

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.0.Final</version>
</dependency>

we have @FutureOrPresent and many other helpful annotations that you can use.

我们有@FutureOrPresent 和许多其他有用的注释供您使用。

回答by JoB?N

The easiest way is not make that field disabled(not editable) and populate with current date.. So you don't need a validation.

If you don't like this approach create an annotation of your own refer this url
Annotation for hibernate validator for a date at least 24 hours in the future

最简单的方法是不禁用该字段(不可编辑)并使用当前日期填充.. 所以你不需要验证。

如果您不喜欢这种方法,请创建您自己的注释,请参考此 url
Annotation for hibernate validator for a date at a date at least 24 hours in the future

Instead of 24 hour check, you need to check whether date value is equal to current date

您需要检查日期值是否等于当前日期,而不是 24 小时检查