【发布时间】: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 而不是持久化。