gpt4 book ai didi

java - hibernate - 从多对多中删除

转载 作者:行者123 更新时间:2023-12-01 12:32:25 24 4
gpt4 key购买 nike

我有以下两个 POJO:

@Entity(name = "project")
@Table(name = "project")
public class Project {
@Column(name = "identifier")
@Id
@GeneratedValue
private Integer identifier;

@ManyToMany(cascade = CascadeType.ALL)
private Set<Member> members = new HashSet<Member>();

// --- constructors ---

public Project() {
}

// --- getters ---

public Integer getIdentifier() {
return identifier;
}

public Set<Member> getMembers() {
return members;
}
}

@Entity(name = "member")
@Table(name = "member")
public class Member {
@Column(name = "identifier")
@Id
@GeneratedValue
private Integer identifier;

@Column(name = "name", columnDefinition = "text")
private String name;

@ManyToMany(mappedBy = "members")
private Set<Project> projects = new HashSet<Project>();

// --- constructors ---

public Member() {
}

// --- getters ---

public Integer getIdentifier() {
return identifier;
}

public String getName() {
return name;
}

public Set<Project> getProjects() {
return projects;
}
}

从多对多关系中删除的常见做法是什么?以下代码可以完美运行,但会产生大量开销。首先,有一些疑问:

  1. 1 个获取项目的查询,由 member.getProjects() 触发
  2. N 个查询来获取每个项目的所有成员,由 project.getMembers() 触发

其次,获取项目(查询 1)和成员(查询 2)的完整数据集,而不仅仅是标识符。

final Member member = ...;
for (final Project project : member.getProjects()) {
project.getMembers().remove(member);
}
db.delete(member);

是否可以在不被迫编写临时查询的情况下更有效地完成此操作?

最佳答案

看这里:

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

此外,您还可以选择使用 jpql 语句来删除数据:

http://docs.oracle.com/html/E24396_01/ejb3_overview_query.html#ejb3_overview_query_delete

但我认为第一个链接就是您正在寻找的内容。

关于java - hibernate - 从多对多中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25837499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com