10

私の要件のためにHibernate Validatorを使用することを検討しています。プロパティに複数の検証チェックがある JavaBean を検証したいと考えています。例えば:

class MyValidationBean
{
   @NotNull
   @Length( min = 5, max = 10 )
   private String myProperty;
}

しかし、このプロパティが検証に失敗した場合、@Required または @Length が原因で失敗したかどうかに関係なく、特定のエラー コードを ConstraintViolation に関連付けたいと思いますが、エラー メッセージは保持したいと考えています。

class MyValidationBean
{
   @NotNull
   @Length( min = 5, max = 10 )
   @ErrorCode( "1234" )
   private String myProperty;
}

上記のようなものが良いでしょうが、そのように構造化する必要はありません。Hibernate Validator でこれを行う方法がわかりません。出来ますか?

4

3 に答える 3

9

カスタム注釈を作成して、探している動作を取得し、検証して反射を使用すると、注釈の値を抽出できます。次のようなもの:

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ErrorCode {
    String value();
}

あなたの豆で:

@NotNull
@Length( min = 5, max = 10 )
@ErrorCode("1234")
public String myProperty;

Bean の検証について:

Set<ConstraintViolation<MyValidationBean>> constraintViolations = validator.validate(myValidationBean);    
for (ConstraintViolation<MyValidationBean>cv: constraintViolations) {
    ErrorCode errorCode = cv.getRootBeanClass().getField(cv.getPropertyPath().toString()).getAnnotation(ErrorCode.class);
    System.out.println("ErrorCode:" + errorCode.value());
}

とは言っても、これらのタイプのメッセージのエラー コードが必要な場合の要件について疑問を呈することになるでしょう。

于 2010-05-26T09:04:04.337 に答える
3

セクション4.2 から。仕様の制約違反:

このgetMessageTemplateメソッドは、補間されていないエラー メッセージ (通常はmessage、制約宣言の属性) を返します。フレームワークは、これをエラー コード キーとして使用できます。

これがあなたの最良の選択肢だと思います。

于 2010-04-18T23:15:42.147 に答える
0

私がやろうとしているのは、アプリケーションの DAO レイヤーでこの動作を分離することです。

あなたの例を使用すると、次のようになります。

public class MyValidationBeanDAO {
    public void persist(MyValidationBean element) throws DAOException{
        Set<ConstraintViolation> constraintViolations = validator.validate(element);
        if(!constraintViolations.isEmpty()){
            throw new DAOException("1234", contraintViolations);
        }
        // it's ok, just persist it
        session.saveOrUpdate(element);
    }
}

そして、次の例外クラス:

public class DAOException extends Exception {
private final String errorCode;
private final Set<ConstraintViolation> constraintViolations;

public DAOException(String errorCode, Set<ConstraintViolation> constraintViolations){
    super(String.format("Errorcode %s", errorCode));
    this.errorCode = errorCode;
    this.constraintViolations = constraintViolations;
}
// getters for properties here
}

ここから検証されていないプロパティに基づいて注釈情報を追加できますが、常に DAO メソッドでこれを実行します。

これが役に立ったことを願っています。

于 2010-05-21T14:08:24.917 に答える