如何使用Join定义JPA存储库查询?

时间:2014-10-08 15:58:56

标签: java mysql sql hibernate jpa

我想通过注释@Query通过Jpa存储库进行连接查询我有三个表。

原生查询是:

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

@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);

日志说

  

意外令牌

请问任何想法?

我的表实体

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;
...
}

1 个答案:

答案 0 :(得分:10)

您在JPA中不需要ON子句,因为JPA已经知道实体如何关联,这要归功于映射注释。

此外,您还要选择application,这不是您查询中定义的别名。

你的联盟毫无意义。

查询应该只是

select application FROM Application a
join a.customer c 
join c.users u
where u.id = :userId

阅读Hibernate文档以了解HQL和连接的工作原理。