级联持久化无法为新实体生成主键,为什么?

发布于 2024-10-02 17:51:25 字数 1148 浏览 5 评论 0原文

这是代码:

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦断已成空 2024-10-09 17:51:25

您的一对多关系被映射为双向(由于 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文