如何通过Spring数据(JPQL)通过子选择获取的左连接来获取集合?

时间:2016-06-29 10:38:11

标签: hibernate jpa spring-data spring-data-jpa jpql

是否可以通过子选择获取集合并将其设置为实体?我需要通过限制找到实体,然后我需要将它们加入另一个实体。

例如,我需要找到公司与员工在公司工作的特定日期

从纯SQL我需要这样的东西:

 select * from Company c 
   LEFT JOIN (
    select * from Employee where  hireDate > 10.5.2015 AND departureDate < 10.12.2015
 ) e 
 on c.id = e.companyId

我在Spring数据中通过此查询尝试了它,但它不起作用

@Query("SELECT c FROM Company c LEFT JOIN FETCH (c.employees e where e.hireDate > ?1 AND e.departureDate < ?1)) WHERE c.id = ?2)
List<Company> findCompanyWitEmployes(Long salary, Long companyId);

实体:

 public class Employee{

      Long id

      String name; 

      Date hireDate;
      Date departureDate;

      @ManyToOne
      @JoinColumn(name = "companyId", insertable = false, updatable = false)
      Company company;
    }


    public class Company{

      Long id

      String name; 

      @OneToMany(mappedBy="company", cascade=CascadeType.REFRESH, fetch = FetchType.LAZY)
        private Set<Employee> employees;
    }

我收到此错误:

2016-06-29 11:50:35.824 [ServerService Thread Pool -- 134] ERROR o.h.hql.internal.ast.ErrorCounter - line 1:81: expecting IDENT, found '('
2016-06-29 11:50:35.824 [ServerService Thread Pool -- 134] ERROR o.h.hql.internal.ast.ErrorCounter - line 1:81: expecting IDENT, found '('
antlr.MismatchedTokenException: expecting IDENT, found '('
    at antlr.Parser.match(Parser.java:211) ~[antlr-2.7.7.jar:na]

1 个答案:

答案 0 :(得分:0)

至于我可以看到你忘了把“放在右括号之前。这就是你得到那个错误的原因。”

  

@Query(“SELECT c FROM Company c LEFT JOIN FETCH(c.employees e where   e.hireDate&gt; ?1和e.departureDate&lt; ?1))WHERE c.id =?2“)