实体类:
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 测试版 2
问题:
有没有人对为什么 Bean 验证器在不可空但自动生成的 id 字段上抛出此异常有任何建议?什么是正确的做法?
最佳答案
对于 IDENTITY 生成,首先将带有空标识符的实体插入数据库,然后执行查询以获取生成的 ID 的值。因此,在插入时,您的 ID 为空,因此违反了 NotNull 约束。
关于jpa - 为什么 Bean 验证器在不可为空但自动生成的 id 字段上抛出 ConstraintViolationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5497841/