我在用户实体和工作实体之间具有以下双向 1:n 关系:
用户等级:
...
@OneToMany(mappedBy = "user",cascade={CascadeType.PERSIST})
public Collection<Job> getJobs() {
return jobs;
}
public void addJob(Job j) {
jobs.add(j);
j.setUser(this);
}
...
职位类别:
// Job class
...
@ManyToOne
public User getUser() {
return user;
}
现在保存一个用户对象(并让休眠自动保存作业实体)工作......然后当我想从数据库中删除作业实体时,我得到一个异常......
User user = new User();
user.addJob(new Job());
entityManager.getTransaction().begin();
entityManager.persist(user);
entityManager.getTransaction().commit();
Job j = entityManager.find(Job.class, 1L);
entityManager.getTransaction().begin();
entityManager.remove(j);
entityManager.getTransaction().commit();
例外:
Exception in thread "main" javax.persistence.RollbackException: Error while committing the transaction
Caused by: javax.persistence.EntityNotFoundException: deleted entity passed to persist: [dst1.model.Job#<null>]
为什么会这样?顺便提一句。当我用作业对象显式调用persist时,问题不会发生……但我不想单独坚持作业,而是让hibernate坚持它们(使用cascade,这实际上是可行的……)
谢谢