休眠
你可以使用
@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;
嗯,那是详尽无遗的。我自己没有测试过,因为我现在没有设置可以这样做,但它应该可以工作。希望对你有帮助。