如何使用Join定义JPA存储库查询? [英] How to define JPA Repository Query with a Join?
问题描述
我想通过注释@Query创建一个Jpa存储库的Join查询我有三个表。
I would like to make a Join query by Jpa repository by annotation @Query I have three tables.
本机查询是:
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;
现在我有Table Hibernate实体,所以我尝试了ApplicationRepository
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);
日志显示
意外令牌
unexpected token
有任何想法吗?
我的表实体
Application.java:
Application.java:
@Entity
@Table
public class Application extends BaseSimpleEntity {
...
@ManyToOne(optional = false)
private Customer customer;
...
}
Customer.java :
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 :
User.java:
@Entity
@Table
public class User extends BaseSimpleEntity {
...
@ManyToOne(optional = false)
private Customer customer;
...
}
推荐答案
JPA中不需要ON子句,因为JPA已经知道实体如何关联,这要归功于映射注释。
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.
你的联接毫无意义。
查询应该只是
select application FROM Application a
join a.customer c
join c.users u
where u.id = :userId
阅读Hibernate文档以了解HQL和联接的工作原理。
Read the Hibernate documentation to understand how HQL and joins work.
这篇关于如何使用Join定义JPA存储库查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!