Cecil Westerhof
Cecil Westerhof

Reputation: 183

From Hibernate to straight JPA

We are asked to change some software. At the moment one of the things that has to be replaced is Hibernate. They want to use straight JPA, so it is easy to switch from Hibernate, to openJPA, to …

One of the annotations that is used is:

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

with the import:

import org.hibernate.validator.constraints.NotEmpty;

My college wants to use:

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

I do not like this. It certainly is not DRY. (It is used hundreds of times.) I prefer to define our own NotEmpty. But I have never worked with annotations. How to do this?

---- Added current solution:

Renamed the function, because in the future it will probably going to be extended.

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 { };
}

Upvotes: 0

Views: 277

Answers (1)

rgrebski
rgrebski

Reputation: 2594

Look at the @NotEmpty source code - in fact it only wraps both validators @NotNull and @Size(min=1).

You can simply create your own class that looks exacly the same as Hibernate Validator's @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();
    }
}

Upvotes: 1

Related Questions