【问题标题】:Cascade persistence fails to generate primary key for a new entity, why?级联持久化无法为新实体生成主键,为什么?
【发布时间】:2010-11-17 12:01:44
【问题描述】:

这是代码:

@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?

【问题讨论】:

  • 你应该检查你的代码:@Column private Integer age;公共雇员(整数年龄){ this.age = 年龄; }
  • 您是否有来自员工方面的部门属性。这似乎在代码中丢失了。映射方式,方是拥有实体。尝试删除 mappedby 而不是持久化。

标签: java jpa openjpa


【解决方案1】:

你的一对多关系被映射为双向(由于mappedBy),但我看不到另一边。也许这就是原因。

即使多对一方实际存在,它也不会在您的代码中初始化,尽管它是关系的拥有方,因此它指定要在数据库中反映的状态。

如果你实际上是指单向关系,你需要删除mappedBy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-23
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    相关资源
    最近更新 更多