2010-04-18 3 views
8

내 요구 사항을 위해 Hibernate Validator를 사용하고 있습니다. 속성에 여러 개의 유효성 검사가있을 수있는 JavaBean의 유효성을 검사하려고합니다. 예를 들면 : Hibernate Validator에서 프로퍼티마다 에러 코드 생성

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.2. ConstraintViolation에서

답변

0

:

getMessageTemplate 방법은 비 보간 오류 메시지 (제약 선언에 보통 message 속성)을 반환합니다. 프레임 워크는 이것을 오류 코드 키로 사용할 수 있습니다.

나는 이것이 최선의 선택이라고 생각합니다.

+1

답장을 보내 주셔서 감사합니다. 불행히도 이것이 원래의 오류 메시지를 보존 할 것이라고는 생각하지 않습니다. 나는 이것의 추가 오류 코드를 찾고있다. 안타깝게도 ConstraintViolation 용 API를 보면 유망 해 보이는 항목이 없습니다. –

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

사용자 정의 주석을 작성하여 찾고자하는 동작을 얻은 다음 refelection의 유효성 검사 및 사용시 주석 값을 추출 할 수 있습니다. 다음과 같은 뭔가 :

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

여러분의 빈에서 : 당신의 빈 검증에

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

:

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