gpt4 book ai didi

jpa - 为什么 Bean 验证器在不可为空但自动生成的 id 字段上抛出 ConstraintViolationException?

转载 作者:行者123 更新时间:2023-12-05 00:25:56 25 4
gpt4 key购买 nike

实体类:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com