简体   繁体   中英

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

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. 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. 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.

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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