【问题标题】:From Hibernate to straight JPA从 Hibernate 到直接的 JPA
【发布时间】:2015-07-10 18:18:31
【问题描述】:

我们被要求更改一些软件。此刻的一件事 必须更换的是Hibernate。他们想直接使用 JPA, 所以很容易从 Hibernate 切换到 openJPA,再到……

使用的注释之一是:

@NotEmpty(message = "Field is not filled")

导入:

import org.hibernate.validator.constraints.NotEmpty;

我的大学想使用:

@NotNull(message = "Field is not filled")
@Size(message = "Field is not filled", min = 1)

我不喜欢这样。它当然不是 DRY。 (它被用于数百 次。)我更喜欢定义我们自己的 NotEmpty。但我从来没有工作过 带注释。如何做到这一点?

---- 添加当前解决方案:

重命名函数,因为将来它可能会被扩展。

import        java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.FIELD;
import        java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import        java.lang.annotation.Target;

import        javax.validation.Constraint;
import        javax.validation.constraints.NotNull;
import        javax.validation.constraints.Size;
import        javax.validation.ReportAsSingleViolation;

@Documented
@Constraint(validatedBy = { })
@Target({ FIELD })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotNull
@Size(min = 1)
public @interface CheckInput {
    public abstract String   message() default "Field is not filled";

    public abstract String[] groups()  default { };
}

【问题讨论】:

  • 显然“NotNull”和“Size”不是 JPA 注释。它们是“bean 验证”注解,不同的 java 规范,但它们至少是标准化的
  • 看看Java Custom Annotations Example这可能对你有帮助。

标签: java hibernate jpa annotations


【解决方案1】:

查看@NotEmpty 源代码 - 实际上它只包装了验证器@NotNull 和@Size(min=1)。

您可以简单地创建自己的类,该类看起来与 Hibernate Validator 的 @NotEmpty 完全相同:

@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@ReportAsSingleViolation
@NotNull
@Size(min = 1)
public @interface NotEmpty {
    String message() default "{org.hibernate.validator.constraints.NotEmpty.message}";

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

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

    /**
     * Defines several {@code @NotEmpty} annotations on the same element.
     */
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        NotEmpty[] value();
    }
}

【讨论】:

  • 我在这方面有很长的路要走。需要找到正确的进口,但设法做到了。需要一些测试,但我目前没有环境。 @Retention(RUNTIME) 是必要的吗?因为它已经在 ReportAsSingleViolation 中。
  • 是的,需要保留(注解没有继承)
  • 好的,谢谢。到时我会保留它。 (你很快。)现在我需要理解代码。 ;-)
猜你喜欢
  • 2015-03-03
  • 1970-01-01
  • 2018-10-20
  • 2020-01-10
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
相关资源
最近更新 更多