【问题标题】:Inner Join and Group By using Specification in Spring Data JPA在 Spring Data JPA 中使用规范进行内部联接和分组
【发布时间】:2016-09-18 12:45:54
【问题描述】:

我正在尝试获取 emptype 为 clerk 且入职日期为最近的员工详细信息。

SQL Server 2008 中的查询如下所示:

select 
 * 
from 
  employee jj 
  inner join
  (
    select 
      max(join_date) as jdate,
      empltype as emptype 
    from 
      employee 
    where 
      empltype='clerk' 
    group by empltype
  ) mm 
    on jj.join_date=mm.jdate and jj.empltype=mm.emptype;

我使用 SpringData JPA 作为我的持久层,使用 QuerylDSL、规范和谓词来获取数据。

我正在尝试在 QueryDSL 或 Specification 中转换上述查询,但无法正确挂钩。

员工实体:

int seqid;(sequence id)
String empltype:
Date joindate;
String role;

规范类中的谓词方法:

Predicate toPredicate(Root<employee> root,CriteriaQuery <?> query,CriteriaBuilder cb)
{
            Predicate pred=null;
            // Returning the rows matching the joining date
            pred=cb.equal(root<Emplyoee_>.get("joindate"));
            //**//

}

应该在 //**// 中编写什么代码来将 SQL 查询转换为 JPA 谓词。任何其他返回 Page 的 Spring Data JPA impl (如 @Query、NamedQuery 或 QueryDSL)也适用于我。

提前致谢

【问题讨论】:

  • Employee findTopByEmpltypeOrderByJoindateDesc(String employeeType) 不够吗?

标签: spring spring-data spring-data-jpa criteria querydsl


【解决方案1】:

我在记事本中写了这个,还没有经过测试,但我认为你正在寻找类似的东西

QEmployee e1 = new QEmployee("e1");
QEmployee e2 = new QEmployee("e2");

PathBuilder<Object[]> eAlias = new PathBuilder<Object[]>(Object[].class, "eAlias");
JPASubQuery subQuery = JPASubQuery().from(e2)
                                    .groupBy(e2.empltype)
                                    .where(e2.empltype.eq('clerk'))
                                    .list(e2.join_date.max().as("jdate"), e2.emptype)

jpaQuery.from(e1)
        .innerJoin(subQuery, eAlias)
        .on(e1.join_date.eq(eAlias.get("jdate")), e1.emptype.eq(eAlias.get("emptype")))
        .list(qEmployee);

【讨论】:

    猜你喜欢
    • 2019-12-01
    • 2021-10-16
    • 2016-02-17
    • 2017-05-12
    • 2019-05-25
    • 2016-07-22
    • 2017-06-01
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多