通过UPDATE .. SET查询更新实体关系 [英] Update Entity Relationship via UPDATE .. SET Query

查看:146
本文介绍了通过UPDATE .. SET查询更新实体关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体:

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

要删除一个b,我首先需要使该关系无效. 传统上",我会做类似的事情:

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

如果a的列表越来越大(在我的情况下为几百),这不是很好的表现.

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

我知道我也可以使用JPQL创建更新查询.

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

类似这样的东西:

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

问题:要从ab列表中删除一个 b的相应JPQL查询是什么?

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

简而言之: 如何翻译

a.getBs().remove(b);

进入JPQL查询?

编辑:上述更新查询翻译为

the mentioned update query translates to

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

表格如下:

A
ID

B
ID    A_ID

推荐答案

从评论和

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

因此,要做

a.getBs().remove(b);

作为jpql查询,可以做到

as an jpql query, one can do

"UPDATE B b SET b.a = NULL"

这将释放ab之间的双向关系.

This will release the bidirectional relationship between a and b.

请注意,您可能需要清除L2缓存或关闭EntitiyManagerFactory才能使它生效.

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

factory.getCache().evictAll();

这篇关于通过UPDATE .. SET查询更新实体关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆