我应该让JPA还是数据库级联删除? [英] Should I let JPA or the database cascade deletions?

查看:122
本文介绍了我应该让JPA还是数据库级联删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有两个实体A和B.B与A具有多对一的关系,如下所示:

@Entity
public class A {
  @OneToMany(mappedBy="a_id")
  private List<B> children;
}

@Entity
public class B {
  private String data;
}

现在,我想删除A对象,并将删除操作级联到其所有子对象(B).有两种方法可以做到这一点:

1)将cascade=CascadeType.ALL, orphanRemoval=true添加到OneToMany批注中,让JPA删除所有子项,然后再从数据库中删除A对象.

2)保留类不变,只需让数据库级联删除操作即可.

使用后面的选项是否有问题?这会导致实体管理器保留对已删除对象的引用吗?我之所以选择选项2而不是选项1的原因是,选项1生成了n + 1条用于删除的SQL查询,当对象A包含许多子项时,这可能花费较长的时间,而选项2仅生成一个SQL查询,然后继续进行操作.快乐地.有什么最佳实践"吗?

解决方案

在EclipseLink中,如果使用@CascadeOnDelete批注,则可以同时使用两者. EclipseLink还将为您生成级联DDL.

看, http://wiki.eclipse.org/EclipseLink/Examples/JPA/DeleteCascade

这通过让数据库进行删除来优化删除,但同时通过删除对象来维护缓存和持久性单元.

请注意,orphanRemoval = true还将删除从集合中删除的对象,而数据库级联约束将无法为您提供这些对象,因此仍然需要在JPA中使用规则.数据库还存在一些无法处理删除的关系,因为数据库只能沿约束的反方向层叠,带有外键的OneToOne或带有联接表的OneToMany不能层叠在数据库上.

Let's say we have two entities, A and B. B has a many-to-one relationship to A like follows:

@Entity
public class A {
  @OneToMany(mappedBy="a_id")
  private List<B> children;
}

@Entity
public class B {
  private String data;
}

Now, I want to delete the A object and cascade the deletions to all its children (B). There are two ways to do this:

1) Add cascade=CascadeType.ALL, orphanRemoval=true to the OneToMany annotation, letting JPA remove all children before removing the A-object from the database.

2) Leave the classes as they are and simply let the database cascade the deletion.

Is there any problem with using the later option? Will it cause the Entity Manager to keep references to already deleted objects? My reason for choosing option two over one is that option one generates n+1 SQL queries for a removal, which can take a prolonged time when object A contains a lot of children, while option two only generates a single SQL query and then moves on happily. Is there any "best practice" regarding this?

解决方案

In EclipseLink you can use both if you use the @CascadeOnDelete annotation. EclipseLink will also generate the cascade DDL for you.

See, http://wiki.eclipse.org/EclipseLink/Examples/JPA/DeleteCascade

This optimizes the deletion by letting the database do it, but also maintains the cache and the persistence unit by removing the objects.

Note that orphanRemoval=true will also delete objects removed from the collection, which the database cascade constraint will not do for you, so having the rules in JPA is still necessary. There are also some relationships that the database cannot handle deletion for, as the database can only cascade in the inverse direction of the constraint, a OneToOne with a foreign key, or a OneToMany with a join table cannot be cascaded on the database.

这篇关于我应该让JPA还是数据库级联删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆