性能是关键:在数据库内部级联删除/更新还是让 Hibernate/JPA 处理它更好?
如果级联在 DBMS 内部,这会影响查询数据的能力吗?
如果这很重要,我正在使用 HSQLDB。
您好,我在映射实体时遇到问题。我正在使用 JPA2 和 Hibernate 实现。我得到带有 @ManyToMany 注释的表
\n\nhttp://img204.imageshack.us/img204/7558/przykladd.png
\n\n我将其映射为:
\n\n@Entity\n@Table("employee")\nclass Employee {\n @Id\n \xc2\xa0\xc2\xa0@GeneratedValue(strategy = GenerationType.IDENTITY)\n \xc2\xa0\xc2\xa0private Integer id;\n\n\xc2\xa0\xc2\xa0@Column\n\xc2\xa0\xc2\xa0private String name;\xc2\xa0\n\n \xc2\xa0@ManyToMany\n\xc2\xa0\xc2\xa0@JoinTable(name = "proj_emp",\n\xc2\xa0 \xc2\xa0joinColumns = @JoinColumn(name = "employee_id", referencedColumnName = "id"),\n\xc2\xa0 inverseJoinColumns = @JoinColumn(name = "project_id", referencedColumnName = "id"),\xc2\xa0\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0uniqueConstraints = @UniqueConstraint(columnNames = {"employee_id", "project_id"}))\xc2\xa0\n\xc2\xa0\xc2\xa0private List<Project> projects;\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0...}\n\n\n@Entity\n@Table("project")\nclass Project {\n\xc2\xa0\xc2\xa0\xc2\xa0@Id\n\xc2\xa0\xc2\xa0\xc2\xa0@GeneratedValue(strategy = GenerationType.IDENTITY)\n\xc2\xa0\xc2\xa0\xc2\xa0private Integer id;\xc2\xa0\n\n\xc2\xa0\xc2\xa0\xc2\xa0@Column\xc2\xa0\xc2\xa0\n \xc2\xa0\xc2\xa0private String name;\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\n\xc2\xa0\xc2\xa0\xc2\xa0@Column\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\n\xc2\xa0\xc2\xa0\xc2\xa0private Integer budget;\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\n\n\xc2\xa0\xc2\xa0\xc2\xa0@ManyToMany(mappedBy = "projects")\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\n\xc2\xa0\xc2\xa0\xc2\xa0private List<Employee> employees;\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0...}\nRun Code Online (Sandbox Code Playgroud)\n\n现在,当我从 Employee 中删除记录时,我希望从表 proj_emp 中进行级联删除,但表 Project 中的任何内容都无法删除。
\n\n获得它的最佳方式是什么?
\n\n谢谢\n大卫
\n我当前正在努力删除一个涉及各种关系的实体(仅限@ManyToOne) - 但是,Hibernate不会删除任何内容 - 在调用之后em.remove一切都保持不变.
我有5个实体(E1 - E5),引用有E6问题的实体(),如下所示:
@Entity
public class EX {
@OneToMany(mappedBy = "eX", fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
private Set<E6> e6s;
}
Run Code Online (Sandbox Code Playgroud)
E6本身有相反的@ManyToOne关系:
public class E6{
@ManyToOne(optional = false)
private E1 e1;
@ManyToOne(optional = false)
private E2 e2;
@ManyToOne(optional = false)
private E3 e3;
@ManyToOne(optional = false)
private E4 e4;
@ManyToOne(optional = false)
private E5 e5;
}
Run Code Online (Sandbox Code Playgroud)
(遗漏了ID,其他列等......)
每当我打电话时em.remove(instanceOfE6),根本没有任何反应 …
我在 spring mvc 应用程序中使用 hibernate,并且有一个关于级联的问题。我看到很多类似的问题,但没有一个能回答我的问题。假设我有User和UserPosition对象。User有一个集合UserPosition,也有一个UserPosition作为默认位置。结构是这样的:
用户:
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private Collection<UserPosition> userPositionCollection;
public Collection<UserPosition> getUserPositionCollection() {
return userPositionCollection;
}
public void setUserPositionCollection(Collection<UserPosition> collection) {
this.userPositionCollection = collection;
}
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "default_User_Position_ID", referencedColumnName = "id")
private UserPosition defaultUserPosition;
public UserPosition getDefaultUserPosition() {
return defaultUserPosition;
}
public void setDefaultUserPosition(UserPosition defaultUserPosition) {
this.defaultUserPosition = defaultUserPosition;
}
Run Code Online (Sandbox Code Playgroud)
用户位置:
@JoinColumn(name = "user_id", referencedColumnName = "id")
@ManyToOne(fetch …Run Code Online (Sandbox Code Playgroud) 我的数据库中有两个表:一个用于持久化用户,另一个用于保存他们的权限。
问题是,当我尝试删除用户时,必须删除权限,这样我才能避免收到违反约束的异常。我为此使用了 JPA 级联类型.ALL 和 orphanRemoval=true :
@OneToMany(fetch = FetchType.LAZY, mappedBy = "users",cascade = CascadeType.ALL,orphanRemoval = true)
public Set<Authorities> getAuthoritieses() {
return this.authoritieses;
}
Run Code Online (Sandbox Code Playgroud)
问题是只有当将被删除的用户是在另一个会话中创建时,hibernate 才会为权限生成删除查询:当我创建用户时,添加一些权限,然后尝试删除它,引发了违反约束的异常,即在另一个会话中创建用户时则不是这种情况(然后休眠将为权限生成删除查询)。
这是引发的异常(此处的“notification_config”指的是用户权限表和“liste_envoi”):
sept. 07, 2015 7:42:14 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
Avertissement: #{listeEnvoiBean.suppListe()}: org.springframework.dao.DataIntegrityViolationException: ERREUR: UPDATE ou DELETE sur la table « liste_envoi » viole la contrainte de clé étrangère
« notifconfiglistefk » de la table « notification_config »
Détail : La clé (id)=(5) est toujours référencée à partir de la table « notification_config ».; SQL [n/a]; …Run Code Online (Sandbox Code Playgroud) I'm having problems when saving entities in my DB.
I have something like (very simplified) :
@Entity
public class Building {
@OneToMany(mappedBy = "building", fetch = FetchType.EAGER)
private List<Employee> employees;
}
@Entity
public class Employee {
@NotNull
@ManyToOne
@JoinFetch(INNER)
@JoinColumn
private Building building;
@PostLoad
private void onLoad(){
if (this.plannedOrder == null) {
//For old entities in this DB, update plannedOrder if null
if (this.order < FIRST.getCode()) {
this.plannedOrder = FIRST;
} else if (this.order >= FIRST.getCode() && this.order < SECOND.getCode()) …Run Code Online (Sandbox Code Playgroud) TL;DR:是否可以将 Hibernate 配置为使用单个删除查询删除所有子对象?
完整问题:我在 Hibernate 5.1 中定义了以下父/子关联:
public class Parent {
@OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", cascade = CascadeType.REMOVE)
private List<Child> children;
}
public class Child {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "parent_id", nullable = false)
private Parent parent;
}
Run Code Online (Sandbox Code Playgroud)
当我删除父对象时,所有子对象都按预期删除,但每个子对象都被单独删除。在我的应用程序中,父级可能有数千个子级,因此出于性能原因,我需要使用单个查询一次将它们全部删除。
可能的解决方法
DELETE FROM child WHERE parent_id = ?在删除父级之前手动执行我自己的 HQL 查询。这里的缺点是我(和任何其他开发人员)必须记住调用该方法。另外,它基本上绕过了级联删除。.clear()设置子集合以防止 Hibernate 和数据库之间的差异。编辑:我看到旧版本的 Hibernate 曾经具有一次性删除的概念,但我在最新版本的文档中找不到任何类似的内容。那个功能被删除了?
我有一张员工表。每个员工行包含员工的经理。一名经理将拥有一名或多名员工,一名员工也可能是一名经理。
我正在尝试构建一个查询,该查询将返回给定经理的所有员工。
例如,经理 A 有员工 B、C 和 D。员工 B 是 E、F 和 G 的经理。员工 C 是 H 和 I 的经理。D 没有直接下属。E 有 Y 和 Z 作为直接报告。
所以,如果我查询 A,我希望得到 B、C、D、E、F、G、H、Y 和 Z 作为结果。如果我查询 B,我应该得到 E、F、G、Y 和 Z。
基本上,查询需要继续其级联,直到返回与所选经理有任何联系的所有员工。
我可以通过以下方式获得一级迭代:
select fullname from employees where manager = 'XXX'
or manager in (select fullname from employees where manager='XXXX')
Run Code Online (Sandbox Code Playgroud) 情况似乎很简单(但它不起作用)。Db 部分(EVENT_ID是外键。表FK_RR_E_CI上的约束引用EVENT)
|-------| |----------------|
| EVENT | 1 ------ ? | RECURRENT_RULE |
|-------| |----------------|
| ID | | ID |
|-------| | EVENT_ID |
|----------------|
Run Code Online (Sandbox Code Playgroud)
Java部分:
@Entity
public class Event {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "event")
private Set<RecurrentRule> recurrentRules = new HashSet<>();
}
@Entity
public class RecurrentRule {
@ManyToOne
@JoinColumn(columnDefinition = "event_id")
private Event event;
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试删除事件对象,它将返回:
could not execute statement; SQL [n/a]; constraint [MY_SCHEMA.FK_RR_E_CI];
nested exception is org.hibernate.exception.ConstraintViolationException: …Run Code Online (Sandbox Code Playgroud) java hibernate cascade foreign-key-relationship hibernate-mapping
突然我收到一个错误,说TypeError: on_delete must be callable.我不知道如何解决这个错误,因为我field=models.ForeignKey(default=1, on_delete='CASCADE', to='main.Category'),在我的代码中没有看到任何地方提到。
File "/home/arch/myproject/main/migrations/0014_auto_20191025_1154.py", line 6, in <module>
class Migration(migrations.Migration):
File "/home/arch/myproject/main/migrations/0014_auto_20191025_1154.py", line 47, in Migration
field=models.ForeignKey(default=1, on_delete='CASCADE', to='main.Category'),
File "/home/arch/.local/lib/python3.8/site-packages/django/db/models/fields/related.py", line 801, in __init__
raise TypeError('on_delete must be callable.')
Run Code Online (Sandbox Code Playgroud)
类型错误:on_delete 必须是可调用的。
cascade ×10
hibernate ×7
java ×5
jpa ×5
annotations ×1
django ×1
eclipselink ×1
hsqldb ×1
jpa-2.0 ×1
many-to-one ×1
one-to-many ×1
orm ×1
parent-child ×1
python ×1
select ×1
sql ×1
sql-server ×1