Search code examples
javajpaeclipselinkderbyjpql

Update Entity Relationship via UPDATE .. SET Query


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

Solution

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