I would like to make a Join query by Jpa repository by annotation @Query I have three tables.
The native query is:
select application.APP_ID
from user, customer, application
where user.USE_CUSTOMER_ID = customer.CUS_ID
and application.APP_CUSTOMER_ID = customer.CUS_ID
and user.USE_ID=1;
Now I have Table Hibernate entity, so I tried in ApplicationRepository
@Query(SELECT application FROM Application a
INNER JOIN customer c ON c.customer.id = a.customer.id
INNER JOIN user u ON u.customer.id = c.customer.id
INNER JOIN application a ON a.user.id = u.id
WHERE
u.id = :user.id)
List<Application> findApplicationsByUser(@Param("User") User user);
The log says
unexpected token
Any ideas, please?
My table Entity
Application.java:
@Entity
@Table
public class Application extends BaseSimpleEntity {
...
@ManyToOne(optional = false)
private Customer customer;
...
}
Customer.java:
@Entity
@Table
public class Customer extends BaseSimpleEntity {
...
@OneToMany(mappedBy = "customer")
private List<User> users;
@OneToMany(mappedBy = "customer")
private List<Application> applications;
...
}
User.java:
@Entity
@Table
public class User extends BaseSimpleEntity {
...
@ManyToOne(optional = false)
private Customer customer;
...
}
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.
Joining Tables with JPA Specifications select author0_.id as id1_1_, author0_. first_name as first_na2_1_, author0_. last_name as last_nam3_1_ from author author0_ inner join author_books books1_ on author0_.id = books1_. author_id inner join book book2_ on books1_.
You don't need ON clauses in JPA, because the JPA already know how entities are associated thanks to the mapping annotations.
Moreover, you're selecting application
, which is not an alias defined in your query.
And your joins make no sense.
The query should simply be
select application FROM Application a
join a.customer c
join c.users u
where u.id = :userId
Read the Hibernate documentation to understand how HQL and joins work.
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