【问题标题】:Validate hibernate date as long验证休眠日期只要
【发布时间】:2021-03-17 13:56:33
【问题描述】:

我想验证Long 类型的日期是否大于当前时间。
我见过@Past@Future等等……但不适用于Long数据类型。

我正在寻找这样的东西:

@FutureOrPresent
private Long dateStart;
@Future
private Long dateEnd;

但为 Long 值工作。

如何验证date > System.currentTimeMillis()

提前致谢。

【问题讨论】:

    标签: java hibernate-validator


    【解决方案1】:

    如果您想使用现有的约束注释,但不支持您想要应用它们的类型(在您的情况下为 Long),您需要:

    创建自己的 ConstraintValidator 实现,例如:

    public class FutureLongValidator implements ConstraintValidator<Future, Long> { 
        public boolean isValid(Long value, ConstraintValidatorContext context) {
            if ( value == null ) {
                return true;
            }
            return value > System.currentTimeMillis();
        }
    }
    

    然后注册它,以便 HV 知道它并可以使用它进行验证。有几种方法可以做到这一点。我建议使用 ServiceLoader 方法。为此,必须创建一个文件 META-INF/services/javax.validation.ConstraintValidator,并将验证器的完全限定名称添加到其中:

    some.package.FutureLongValidator
    some.package.FutureOrPresentLongValidator
    

    有关更详细的说明和示例项目,请查看这篇详细介绍该主题的帖子 - Adding custom constraint definitions via the Java service loader

    【讨论】:

      猜你喜欢
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 2012-11-19
      • 2011-02-11
      • 1970-01-01
      相关资源
      最近更新 更多