从 Hibernate 到直接 JPA

From Hibernate to straight JPA

我们被要求更改一些软件。目前的一件事 必须更换的是 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)

我不喜欢这样。它当然不是干的。 (它被使用了数百 次。)我更喜欢定义我们自己的 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 { };
}

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

您可以简单地创建自己的 class,它看起来与 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();
    }
}