2011-03-31 3 views
3

ENTITY 클래스 :null 유효성이 있지만 자동 생성 된 id 필드에서 Bean 유효성 검사기가 ConstraintViolationException을 던지는 이유는 무엇입니까?

public class MyUser implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Basic(optional = false) 
    @NotNull 
    @Column(name = "id") 
    private Integer id; 


    @Basic(optional = false) 
    @NotNull 
    @Size(min = 1, max = 100) 
    @Column(name = "name") 
    private String name; 

    // other attrs and getter-setters 


    public MyUser() { 
    } 

    public MyUser(Integer id) { 
     this.id = id; 
    } 

    public MyUser(Integer id, String name) { 
     this.id = id; 
     this.name = name; 
    } 
} 

사용 코드 :

MyUser myuser = new MyUser(); 
myuser.setName("abc"); 

try { 
    em.persist(myuser); 
} catch (ConstraintViolationException e) { 
    System.out.println("size : " + e.getConstraintViolations().size()); 
    ConstraintViolation<?> violation = e.getConstraintViolations().iterator().next(); 
    System.out.println("field : " + violation.getPropertyPath().toString()); 
    System.out.println("type : " + violation.getConstraintDescriptor().getAnnotation().annotationType()); 
} 

OUTPUT :

INFO: size : 1 
INFO: field : id 
INFO: type : interface javax.validation.constraints.NotNull 

ENVIRONMENT :

JDK 6 U23
글래스 피쉬 서버 오픈 소스 에디션 3.1-B41 (이 콩 validator.jar는)
넷빈즈 IDE 7.0 베타 2

질문 :

합니까 누구가에이 예외를 던지는 콩 검사기 이유에 제안 null이 허용되지 않지만 자동 생성 된 id 필드는 무엇입니까? 옳은 약속은 뭐니?

답변

2

IDENTITY 생성에서는 엔티티가 먼저 null 식별자로 데이터베이스에 삽입되고 나중에 쿼리가 생성되어 생성 된 ID의 값을 가져옵니다. 따라서 삽입시 ID는 null이므로 NotNull 제약 조건을 위반합니다.

+0

그래서 빈 검증을 성공적으로 통과하는 올바른 방법은 무엇입니까? 'Id' 필드를 임시/더미 값으로 설정하는 것은 적절한 접근법이 아닙니다. –

관련 문제