英文:
How to create a correct JPA Many to Many Relationship
问题
我有一个数据库中的 "subcategory" 表和一个 "item" 表。一个项目可以有多个子类别,一个子类别也可以对应多个项目。
在使用 JPA 时,如果我删除一个子类别,它不仅会删除关联关系(从映射表中),还会连同所有关联的项目一起删除。
我需要的是,删除子类别时不删除项目。但是,如果那个子类别是一个项目关联的唯一子类别,则该项目也应该被删除。
请查看这张图片:图片链接
在这里,如果我删除 subcategory1,只有 Item1 应该与其一起被删除。(在当前情况下,它还会删除 Item2)
以下是我的代码:
SubCategory.java 的一部分:
@Entity
@Table(name = "sub_category")
@JsonIgnoreProperties({"items"})
public class SubCategory extends AuditModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(columnDefinition = "TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
nullable = false)
private String name;
@ManyToMany(mappedBy = "subCategories", cascade = CascadeType.ALL)
private List<Item> items = new ArrayList<>();
}
Item.java 的一部分:
@Entity
@Table(name = "Item")
public class Item extends AuditModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(columnDefinition = "TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
nullable = false)
private String name;
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private List<SubCategory> subCategories = new ArrayList<>();
}
附注:我尝试过删除 cascadeType,但不起作用,因为一个项目必须至少有一个子类别。
英文:
I have a "subcategory" table and an "item" table on the database. One item can have many subcategories and one subcategory can have many items.
When using JPA, if I delete a subcategory, it deletes not only the relationship (from the mapping table) but also all the associated items also.
What i need is, deleting a subcategory without deleting the items. But if that subcategory is the only one subcategory associated with an item, the item should be also deleted.
https://i.stack.imgur.com/rxZM3.jpg
Please check the image
So here, if i delete subcategory1, only Item1 should be deleted with it.(In the current situation it deletes Item2 also)
Here's my code:
part of SubCategory.java
@Entity
@Table(name = "sub_category")
@JsonIgnoreProperties({"items"})
public class SubCategory extends AuditModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(columnDefinition = "TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
nullable = false)
private String name;
@ManyToMany(mappedBy = "subCategories", cascade = CascadeType.ALL)
private List<Item> items = new ArrayList<>();
}
part of Item.java
@Entity
@Table(name = "Item")
public class Item extends AuditModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(columnDefinition = "TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci",
nullable = false)
private String name;
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private List<SubCategory> subCategories = new ArrayList<>();
}
PS: I tried removing cascadeType, but it doesn't work because an item must have at least one subcategory
专注分享java语言的经验与见解,让所有开发者获益!
评论