简体   繁体   English

JPA 多对多和单向删除

[英]JPA ManyToMany and unidirectional deletions

I've the following relationship:我有以下关系:

class Product { // 10000s many of them

 @ManyToMany
 List<Category> categories; //usually 0-5 

}

and

class Category {
...with no back link...
}

now if I delete a category and then I load a product that has that category I will get an error that contains:现在,如果我删除一个类别,然后加载具有该类别的产品,我将收到一个错误,其中包含:

update or delete on table "categories" violates foreign key constraint (...) is still referenced from table product_category表“类别”上的更新或删除违反了外键约束(...)仍然从表 product_category 中引用

I've seen a number of answers and tutorials, but the problem is that many do propose to add Product as a bidirectional relationship in Category, then before removing a category I will go through all Products and remove that particular category.我已经看过许多答案和教程,但问题是许多人确实建议在 Category 中添加 Product 作为双向关系,然后在删除类别之前,我将 go 通过所有 Products 并删除该特定类别。 But products are thousands here and the operation will be too long.但是这里的产品成千上万,运行时间太长。

This could be so simple by using normal SQL, but I'd like to keep the automatic loading of of categories and the mapping of the properties.这可以通过使用普通的 SQL 变得如此简单,但我想保持类别的自动加载和属性的映射。 Is there a lightweight way to automatically do this without keeping a list of products in each category ?是否有一种轻量级的方法可以自动执行此操作而无需在每个类别中保留产品列表

What you're trying to do does not make lot of sense IMO.您尝试做的事情没有多大意义IMO。

You want to keep unidirectional relation but want a way to delete the other side directly.您想保持单向关系,但想要一种直接删除另一方的方法。 But I understood that the problem was the huge dataset (category -> product).但我知道问题出在庞大的数据集(类别 -> 产品)。

One way to solve this would be to mix in the same transaction a JPQL(to delete the category) and a native query (to delete rows from the join-table).解决此问题的一种方法是在同一事务中混合 JPQL(删除类别)和本机查询(从连接表中删除行)。

em.createNativeQuery("delete from product_category where category_id = ?").setParameter(1, category.getId()).executeUpdate();
em.remove(category);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM