2015-07-10 64 views
0

我們被要求更換一些軟件。目前,必須替換的東西之一 是Hibernate。他們想用直JPA, 所以很容易從休眠切換,OpenJPA的,到...從休眠到直接JPA

一所使用的註解是:

@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 { }; 
} 
+0

明確「NOTNULL」和「大小」不是JPA註解。它們是「bean驗證」註釋,是一個不同的java規範,但它們至少標準化爲 –

+0

請看[Java Java Custom Annotations Example **](http://www.mkyong.com/java/java-custom -annotations-example /)這可能對你有幫助。 –

回答

1

查看@NotEmpty源代碼 - 實際上它只包含兩個驗證器@NotNull和@Size(min = 1)。

您可以簡單地創建自己的類,看起來exacly一樣Hibernate驗證的@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(); 
    } 
} 
+0

對此我有很長的路要走。需要找到正確的進口,但管理。需要一些測試,但我目前沒有環境。 @ Retention(RUNTIME)是否必需?因爲它已經在ReportAsSingleViolation中。 –

+0

是的,需要保留(註釋沒有繼承) – rgrebski

+0

好的,謝謝。那麼我會保留它。 (你很快。)現在我需要了解代碼。 ;-) –