java 如何使用联接定义 JPA 存储库查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26261324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define JPA Repository Query with a Join?
提问by Mercer
I would like to make a Join query by Jpa repository by annotation @Query I have three tables.
我想通过注释@Query 通过 Jpa 存储库进行 Join 查询我有三个表。
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
现在我有 Table Hibernate 实体,所以我在 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:
应用程序.java:
@Entity
@Table
public class Application extends BaseSimpleEntity {
...
@ManyToOne(optional = false)
private Customer customer;
...
}
Customer.java:
客户.java:
@Entity
@Table
public class Customer extends BaseSimpleEntity {
...
@OneToMany(mappedBy = "customer")
private List<User> users;
@OneToMany(mappedBy = "customer")
private List<Application> applications;
...
}
User.java:
用户.java:
@Entity
@Table
public class User extends BaseSimpleEntity {
...
@ManyToOne(optional = false)
private Customer customer;
...
}
回答by JB Nizet
You don't need ON clauses in JPA, because the JPA already know how entities are associated thanks to the mapping annotations.
您不需要 JPA 中的 ON 子句,因为由于映射注释,JPA 已经知道实体是如何关联的。
Moreover, you're selecting application
, which is not an alias defined in your query.
此外,您正在选择application
,这不是您的查询中定义的别名。
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.
阅读 Hibernate 文档以了解 HQL 和联接的工作原理。