10

I am looking at using Hibernate Validator for a requirement of mine. I want to validate a JavaBean where properties may have multiple validation checks. For example:

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

But if this property fails validation I want a specific error code to be associated with the ConstraintViolation, regardless of whether it failed because of @Required or @Length, although I would like to preserve the error message.

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

Something like the above would be good but it doesn't have to be structured exactly like that. I can't see a way to do this with Hibernate Validator. Is it possible?

4

3 回答 3

9

您可以创建一个自定义注释来获取您正在寻找的行为,然后在验证和使用引用时,您可以提取注释的值。类似于以下内容:

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

在你的 bean 中:

@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 回答