Why is the Bean validator throwing ConstraintViolationException on the not nullable but auto-generated id field?
ENTITY CLASS :
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;
@B开发者_开发百科asic(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;
}
}
USAGE CODE :
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
GlassFish Server Open Source Edition 3.1-b41 (has bean-validator.jar) NetBeans IDE 7.0 Beta 2QUESTION :
Does anyone has suggestion on why is the Bean validator throwing this exception on the not nullable but auto-generated id field? What is the right approuch?
With IDENTITY generation, the entity is first inserted in database with a null identifier, and a query is executed afterwards to get the value of the generated ID. So, at insert time, your ID is null and thus violates the NotNull constraint.
精彩评论