3

实体类:

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 字段上抛出此异常?什么是正确的方法?

4

1 回答 1

2

使用 IDENTITY 生成,实体首先以空标识符插入数据库,然后执行查询以获取生成的 ID 的值。因此,在插入时,您的 ID 为空,因此违反了 NotNull 约束。

于 2011-03-31T09:45:28.093 回答