Where is implementation of @Future defined?

2019-08-24 02:27发布

问题:

Java persistence & hibernate make it easy to add property-level constraints to entities.

@Entity
@Table(name = "party")
public class PartyEntity {
    @Future
    public DateTime start;
}

The javax.validation.constraint.Future annotation is defined without a specific implementation.

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {})
public @interface Future {
    // ...
}

Where is actual validation implemented? How can this be extended to allow an administrator override?

Though not shown here, I am already using groups for another purpose on this constraint.

回答1:

Implementations for many validators supplied by hibernate-validator: http://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/validator-usingvalidator.html#validator-defineconstraints-builtin

If you are using Maven just add following dependency to pom.xml file:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.0.Alpha1</version>
</dependency>

How can this be extended to allow an administrator override?

The simplest way is to write your own instead.



回答2:

JSR 303 validation does not have too much directly to do with JPA. Of course also JPA entities can be validated with it. What it comes to actual question - most likely you want to follow php-coder's advice and implement new annotation and validation of contraints set via annotation usage.

If because of some mysterious reason you really have to change how Future annotation is processed in your implementation, then solution is of course implementation specific. Assuming that you use Hibernate Validator 4.3, actual check of validation constraint takes place in:

  • org.hibernate.validator.internal.constraintvalidators.FutureValidatorForDate
  • org.hibernate.validator.internal.constraintvalidators.FutureValidatorForCalendar

How these implementations get picked can be affected in org.hibernate.validator.internal.metadata.core.ConstraintHelper. I suggest to attach sources of implementation you use to your IDE, because then it is easy to navigate to this kind of details.