error: No validator could be found for type: java.time.LocalDate

后端 未结 3 605
轮回少年
轮回少年 2020-12-31 08:35

I\'m working on a project that uses bean validation (Hibernate Validator 5.1.3.Final). My bean has a attribute with the @Past annotation.

@Past(         


        
相关标签:
3条回答
  • 2020-12-31 08:59

    There is a @Past annotation in the javax.validation.constraints (validation-api-2.0.1.Final)

    And it works pretty well for java.time.LocalDate

    0 讨论(0)
  • 2020-12-31 09:06

    Since LocalDate is still pretty new a lot of libraries don't handle it yet. In the project I am working on I had to write custom user type for LocalDate.

    Take a look at this hibernate issue HHH-8844

    It seems like they have added a new module hibernate-java8 to support java 8's new Date API.

    I know the above information is talking about type mapping but the same might hold true to validation.

    If there is no out of the box solution you might just have to write your own. See the following page for an example of adding joda time validators, java 8 dates should be similar link

    0 讨论(0)
  • 2020-12-31 09:12

    Actually the issue to refer to is HV-874. Hibernate Validator 5.2.x does add support for some of the new Java 8 date/time types. I should stress "some" in this context. In particular LocalDate is not supported. The Javadocs of LocalDate says:

    This class does not store or represent a time or time-zone. Instead, it is a description of the date, as used for birthdays. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

    Without an instant on the timeline it is not possible to say if a given date is in the part or future. First by attaching a timezone it would be possible to state and answer this question.

    If you still think it makes sense in your use case to use the Past and @Future constraints for LocalDate you can always implement your own ConstraintValidator for LocalDate and register it via XML using a constraint-definition element in a constraint mapping file as seen here.

    If you are using Hibernate Validator 5.2, you can also use the Java ServiceLoader approach to register additional ConstraintValidator implementations - see ConstraintDefinitionContributor. The latter is for now a Hibernate Validator specific feature.

    0 讨论(0)
提交回复
热议问题