Let's say I have the following two tables:
@Entity public class Foo {
@Id private int id;
@ManyToOne()
@JoinColumn(name = "bar_id")
private Bar bar;
}
@Entity public class Bar {
@Id private int id;
private Boolean flag;
}
And I want to write a JPQL query that changes some Bar.flag
values based on a collection of Foo
ids.
If this were plain SQL I'd write something like this:
UPDATE Bar SET flag = true WHERE id IN (SELECT bar_id from FOO where id = 3);
You can't translate this to JPQL however, because the bar_id
column isn't mapped to a property of the entity.
As bar_id
isn't directly mapped on the Foo
Entity, how can I achieve this kind of query in JPQL?
In JPQL, JOIN can only appear in a FROM clause. The INNER keyword is optional (i.e. INNER JOIN is equivalent to JOIN).
The Jakarta Persistence Query Language (JPQL; formerly Java Persistence Query Language) is a platform-independent object-oriented query language defined as part of the Jakarta Persistence (JPA; formerly Java Persistence API) specification. JPQL is used to make queries against entities stored in a relational database.
First of all, JPA only creates an implicit inner join when we specify a path expression. For example, when we want to select only the Employees that have a Department, and we don't use a path expression like e. department, we should use the JOIN keyword in our query.
If you want a working bulk update query, the following should work:
UPDATE Bar b SET flag = true WHERE b IN (SELECT f.bar from FOO f where id = 3);
The idea is to work with entities, when you make the subselect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With