开发者

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 becau开发者_如何学运维se 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜