Hibernate Validator - 比较两个日期 - 类级别约束

时间:2016-08-06 11:43:09

标签: spring hibernate spring-mvc annotations hibernate-validator

所以我必须比较提到的两个日期,并且我编写了一个验证器,它似乎有一些错误,这有点奇怪: 注释类:此处导入了@Target注释,但无法识别内部的枚举。

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { ValidAfterDateValidator.class })
@Documented
public @interface ValidAfterDate {


String message() default "The End date should be after the starting date." ;

Class<?>[] groups() default { };

Class<? extends Payload>[] payload() default { };
}

ValidAfterDateValidator.class:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import gestionprojet.java.entities.Project;

public class ValidAfterDateValidator implements ConstraintValidator<ValidAfterDate, Project> {

@Override
public void initialize(ValidAfterDate constraintAnnotation) {
}

@Override
public boolean isValid(Project projet, ConstraintValidatorContext context) {
    if (projet == null) {
        return true;
    }

    return projet.getDate_Debut().compareTo(projet.getDate_Fin()) > 0;
}

这里不允许使用@ValidAferDate:

Project.class:

@ValidAfterDate
public class Project {

 @Future
 @DateTimeFormat(pattern="dd/MM/YY")
 private Date date_Debut;

 @Future
 @DateTimeFormat(pattern="dd/MM/YY")
 private Date date_Fin;
 //Getters & Setters
 }

任何帮助都会受到赞赏。感谢

1 个答案:

答案 0 :(得分:1)

这:

@Target( { TYPE , ANNOTATION_TYPE })

需要更改为:

@Target( {ElementType.ANNOTATION_TYPE, ElementType.TYPE })

并且印象是:

import java.lang.annotation.ElementType;