简体   繁体   中英

How to delete a ManyToMany item using JPQL?

I have two models, say:

BlogPost(title, message)
Tags(name)

Both have a ManyToMany relationship defined.

Using JPQL, I delete a list of BlogPost with this query:

DELETE FROM BlogPost b WHERE b IN :list

(:list is a List from a previous SELECT requet).

Doing so, I have a ConstraintViolationException because of the relation between BlogPost and Tags .

Is there a way to delete the relation without deleting the Tags using JPQL?

Thanks for your help!

You have to remove the association first, before you delete the entity.

JPA create a table BlogPost_Tags which stores ID of BlogPost and Tags.

So when you try to delete a BlogPost, the constraint on the BlogPost_Tags failed.

You need to delete the relation before delete the Post, and there is no easy way in JPQL, you have to use the EntityManager.

I'll answer myself with the solution I came up. I'm not sure it's the best one, but at least, it works.

Since you want to bulk delete something that have a ManyToMany related items, you first have to delete the relation (in the join table), or do a loop and for each item, delete manually (insane and too much heavy).

So, since JPQL does not allow to do it, a possible way is to make a native SQL query for deleting the id you want in the related table, and then, do the bulk delete.

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