Java 如何使用联接定义JPA存储库查询?
我想通过Jpa repository by annotation@query进行连接查询,我有三个表 本机查询是:Java 如何使用联接定义JPA存储库查询?,java,mysql,sql,hibernate,jpa,Java,Mysql,Sql,Hibernate,Jpa,我想通过Jpa repository by annotation@query进行连接查询,我有三个表 本机查询是: 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; 现在我有了表Hibernat
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;
现在我有了表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);
Customer.java:
在JPA中不需要ON子句,因为由于映射注释,JPA已经知道实体是如何关联的 此外,您选择的是
应用程序
,它不是查询中定义的别名
你的加入毫无意义
查询应该是简单的
select application FROM Application a
join a.customer c
join c.users u
where u.id = :userId
阅读Hibernate文档以了解HQL和联接是如何工作的
@Entity
@Table
public class Customer extends BaseSimpleEntity {
...
@OneToMany(mappedBy = "customer")
private List<User> users;
@OneToMany(mappedBy = "customer")
private List<Application> applications;
...
}
@Entity
@Table
public class User extends BaseSimpleEntity {
...
@ManyToOne(optional = false)
private Customer customer;
...
}
select application FROM Application a
join a.customer c
join c.users u
where u.id = :userId