Update Entity Relationship via UPDATE .. SET Query

邮差的信 提交于 2020-01-25 07:37:10

问题


I have two entities:

class A {
@OneToMany(mappedBy = "a")
List<B> bs;
// getter/ setter
}
class B {
@ManyToOne
A a;
// getter/ setter
}

To delete one b, I first need to invalidate that relationship. "Traditionally" I would do something like that:

A a = em.getReference(A.class, entityIdA)
B b = em.getReference(B.class, entityIdB);
a.getBs().remove(b);
b.setA(null);
em.remove(b);

This is not very performant, if the List of a's is getting large (a few hundreds in my case).

I know I can also use JPQL to create an update query.

something like this:

Query q = em.createQuery("UPDATE B b SET b.a = NULL");
q.executeUpdate();

Question: What would be the corresponding JPQL query to remove one b from a's list of bs?

In short: How to translate

a.getBs().remove(b);

into a JPQL query?

EDIT: the mentioned update query translates to

UPDATE B SET A_ID = ? WHERE (ID = ?)
    bind => [null, 2]

Tables look like this:

A
ID

B
ID    A_ID

回答1:


From the comments and from this question, changing the owning side of the relationship is sufficient.

Therefore, to do

a.getBs().remove(b);

as an jpql query, one can do

"UPDATE B b SET b.a = NULL"

This will release the bidirectional relationship between a and b.

Note that you might need to clear the L2 cache or close the EntitiyManagerFactory for this to take effect.

factory.getCache().evictAll();


来源:https://stackoverflow.com/questions/48692098/update-entity-relationship-via-update-set-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!