![](/img/trans.png)
[英]How do I delete orphan entities using hibernate and JPA on a many-to-many relationship?
[英]JPA - Do I need cascade on many-to-many when using existing entities?
假設我有一個單向的多對多關系:
@Entity
@Table(name = "document")
public class Document {
private Integer id;
private Set<Role> roles;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "document_role",
joinColumns = {@JoinColumn(name = "Document_Id")},
inverseJoinColumns = {@JoinColumn(name = "Role_Id")})
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
@Entity
@Table(name = "role")
public class Role {
private Integer id;
...
}
如果未定義級聯類型,並且假定不必創建新的Role實體,是否將以下內容插入document_role中?
Role role1 = em.find(Role.class, 1);
Role role2 = em.find(Role.class, 2);
Role role3 = em.find(Role.class, 3);
Set<Role> roles = new HashSet<>();
roles.add(role1);
roles.add(role2);
roles.add(role3);
Document document = new Document();
document.setRoles(roles);
// Save document, will that save the association?
em.persist(document);
如果我還想更新角色集合並刷新更改怎么辦? 例如,刪除一個角色或添加另一個。
簡短的答案是沒有。
長答案是每個表對於CRUD都是唯一的。
示例:如果文檔表的ID_role列是角色表的外鍵,並且您更新了此數據,則持久化文檔將更新此列,因為這是文檔表的屬性,它將對Role對象不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.