Cascade persistence fails to generate primary key for a new entity, why?
문제
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?
해결책
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
.
제휴하지 않습니다 StackOverflow