我正在使用JPA2(EclipseLink),我的实体对象如下所示:
@Entity
public class Dashboard
{
@Id
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy="dashboard", orphanRemoval = true)
private List<LogResult> logResults;
//getter-setters
}
@Entity
public class LogResult
{
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private long id;
private Dashboard dashboard;
//getter-setters
}
我有这样的代码来删除仪表板:
EntityManager em = PersistenceInitializer.newEntityManager();
em.getTransaction().begin();
em.remove(dashboard);
em.getTransaction().commit();
但是,当我执行上面的代码时,我收到有关logresult表上的外键约束的错误消息。
为什么会这样?不使用CascadeType.ALL意味着应该为我处理所有这些吗?
更新这是控制台上的实际错误输出
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`crs`.`logresult`, CONSTRAINT `FK_LOGRESULT_DASHBOARD_NAME` FOREIGN KEY (`DASHBOARD_NAME`) REFERENCES `dashboard` (`NAME`))
Error Code: 1451
答案 0 :(得分:0)
对于EclipseLink实现,请参阅EclispeLink JPA Extensions指南:http://eclipse.org/eclipselink/documentation/2.4/jpa/extensions/toc.htm
答案 1 :(得分:-1)
同时明确添加cascade = CascadeType.DELETE_ORPHAN
。首先删除父实体时,所有子对象都将成为孤立对象。 CascadeType.DELETE_ORPHAN
级联类型使JPA删除那些孤立对象。
e.g。下面:
@OneToMany(cascade={CascadeType.ALL, CascadeType.DELETE_ORPHAN})