休眠
您可以使用
@CreationTimestamp
@Temporal(TemporalType.DATE)
@Column(name = "create_date")
private Date startDate;
或更新时
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modify_date")
private Date startDate;
爪哇 (JPA)
您可以定义一个字段Date startDate;
and use
@PrePersist
protected void onCreateStartDate() {
startDate = new Date();
或更新时
@PreUpdate
protected void onUpdateStartDate() {
startDate = new Date();
更新和示例
在您更新问题以不将开始日期固定为现在之后,您必须采取不同的方法。您需要编写一个自定义验证器来检查日期是现在还是将来,例如here https://stackoverflow.com/questions/29637732/annotation-for-hibernate-validator-for-a-date-at-least-24-hours-in-the-future.
因此你可以在中引入一个新的注释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;
嗯,这已经很详尽了。我自己还没有测试过,因为我现在没有这样做的设置,但它应该可以工作。我希望它有帮助。