级联持久化无法为新实体生成主键,为什么?
这是代码:
@Entity
public class Dept {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@OneToMany(
mappedBy = "dept",
cascade = CascadeType.ALL
)
private List<Employee> employees = new ArrayList<Employee>();
public void addEmployee(Employee emp) {
this.employees.add(emp);
}
}
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column private Integer age;
public Employee(Integer a) {
this.age = a;
}
}
然后在单元测试中我这样做(使用 OpenJPA):
// ...
Dept dept = new Dept();
dept.addEmployee(new Employee(25));
this.em.persist(dept);
OpenJPA 说:
Caused by: <openjpa-1.2.1-r752877:753278 nonfatal general error>
org.apache.openjpa.persistence.PersistenceException: Attempt to insert
null into a non-nullable column: column: ID table: EMPLOYEE in
statement [INSERT INTO employee (age) VALUES (?)]
{prepstmnt 841687127 INSERT INTO employee (age) VALUES (?)
[params=(int) 25]} [code=-10, state=23000]
为什么 ID 不是自动生成的?
This is the code:
@Entity
public class Dept {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@OneToMany(
mappedBy = "dept",
cascade = CascadeType.ALL
)
private List<Employee> employees = new ArrayList<Employee>();
public void addEmployee(Employee emp) {
this.employees.add(emp);
}
}
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column private Integer age;
public Employee(Integer a) {
this.age = a;
}
}
Then in a unit test I'm doing this (OpenJPA is used):
// ...
Dept dept = new Dept();
dept.addEmployee(new Employee(25));
this.em.persist(dept);
OpenJPA says:
Caused by: <openjpa-1.2.1-r752877:753278 nonfatal general error>
org.apache.openjpa.persistence.PersistenceException: Attempt to insert
null into a non-nullable column: column: ID table: EMPLOYEE in
statement [INSERT INTO employee (age) VALUES (?)]
{prepstmnt 841687127 INSERT INTO employee (age) VALUES (?)
[params=(int) 25]} [code=-10, state=23000]
Why ID is not auto-generated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的一对多关系被映射为双向(由于
mappedBy
),但我看不到另一边。也许这就是原因。即使多对一方确实存在,它也不会在代码中初始化,尽管它是关系的拥有方,因此它指定要反映在数据库中的状态。
如果您实际上指的是单向关系,则需要删除
mappedBy
。You one-to-many relationship is mapped as bidirectional (due to
mappedBy
), but I can't see the other side. Perhaps it's the cause.And even if many-to-one side actually exists, it's not initialized in your code though it's an owning side of the relationship, therefore it specifies the state to be reflected in the database.
If you actually mean unidirectional relationship, you need to remove
mappedBy
.