Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I refer to columns only mapped for joins in JPQL?

Tags:

java

jpa

jpql

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?

like image 681
SCdF Avatar asked Nov 19 '15 17:11

SCdF


People also ask

Can we use inner join 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).

What do you understand BY JPQL query?

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.

What is join in JPA?

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.


1 Answers

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.

like image 121
V G Avatar answered Sep 18 '22 15:09

V G