多对多级联删除 [英] many-to-many cascade delete
问题描述
我有很多标签<-> 软件,当我删除标签时,我想删除与该标签相关的所有软件,但不能删除与另一个标签有关.这里的业务逻辑如下:没有标签就无法存在软件.下面有包含两个类和一个测试的代码.
I have many-to-many for tag <-> software, when i delete tag i want delete all softwares which are related to that tag BUT not which are related to another tag. The business logic here is the following: Sofware can not exist without a tag. There are code with two classes and one test below.
现在,即使所有软件与其他标签相关,它也会删除所有软件.
Now it deletes all softwares even if they are related to other tags.
如何处理?
@Entity
public class Tag extends Model {
@Column(nullable = false, unique = true)
public String title;
public Tag(String title) {
this.title = title;
}
@ManyToMany(cascade = CascadeType.ALL, mappedBy = "tags")
public List<Software> softwares = new LinkedList<Software>();
}
@Entity
public class Software extends Model {
public String title;
public String description;
@ManyToOne(optional = false)
public Author author;
@ManyToMany
public List<Tag> tags = new LinkedList<Tag>();
public Software(String title, String description, Author author) {
this.title = title;
this.description = description;
this.author = author;
}
public Software(String title, String description, Author author, Tag ... tags) {
this(title, description, author);
if (!Arrays.asList(tags).contains(null)) {
// it needed if we wand to delete Tags with cascade - when delete Tag, then delete all Softwares related to it
for (Tag tag : tags) {
this.tags.add(tag);
}
for (Tag tag : tags) {
tag.softwares.add(this);
}
}
}
}
有一个测试:
@Test
public void testDelete() throws InterruptedException {
Tag tag1 = new Tag("tag1").save();
Tag tag2 = new Tag("tag2").save();
Author author1 = new Author("name", "email").save();
new Software("title1", "description1", author1, tag1).save();
new Software("title3", "description3", author1, tag1, tag2).save();
tag1.delete();
// try to find the software
assertEquals(1, Software.findAll().size()); // IT FAILS - IT DELETES ALL
}
推荐答案
触发器或服务层中的逻辑是实现此目标的最佳选择.如果您确实希望通过模型对其进行标准化,请在此处进行删除操作的选择.
Triggers, or logic in your service layer is the best bet to achieve it. If you really want it via model, normalize it, here you have a choice to do in the behavior on delete.
这篇关于多对多级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!