实体类:
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());
}
输出 :
INFO: size : 1
INFO: field : id
INFO: type : interface javax.validation.constraints.NotNull
环境 :
JDK 6 u23
GlassFish Server 开源版 3.1-b41(有 bean-validator.jar)
NetBeans IDE 7.0 Beta 2
问题 :
有没有人建议为什么 Bean 验证器在不可为空但自动生成的 id 字段上抛出此异常?什么是正确的方法?