2010-04-18 57 views
8

我正在寻找使用Hibernate验证器来满足我的要求。我想验证一个JavaBean,其中属性可能有多个验证检查。例如:在Hibernate验证器中为每个属性生成错误代码

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

但是,如果该物业的验证失败我希望有一个特定的错误代码与ConstraintViolation相关,无论它是否失败,因为@Required或@Length的,但我想保留错误信息。

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

像上面这样的东西会很好,但它不必像这样构造。我看不到用Hibernate Validator做这件事的方法。可能吗?

回答

0

从本说明书的部分4.2. ConstraintViolation

getMessageTemplate方法返回非内插的错误信息(通常在约束声明的message属性)。框架可以将其用作错误代码键。

我认为这是您的最佳选择。

+1

感谢您的回复。不幸的是,我不认为这会保留我想要的原始错误信息。我正在寻找额外的错误代码。可悲的是看着ConstraintViolation的API,我并没有看到任何看起来很有希望的东西。 – 2010-04-19 19:11:25

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方法上。

我希望这有助于。

4

您可以创建一个自定义注释来获取您正在查找的行为,然后验证并使用反射来提取注释的值。像下面这样:

@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()); 
} 

说了这么多,我可能会质疑想要错误代码为这些要求消息的类型。

+0

这是一个很好的解决方案,非常感谢张贴。只需注意一点。代码应该读取getDeclaredField以使其能够访问专用字段。 – MandyW 2013-07-29 20:16:01