【问题标题】:Path references in QueryDSL join to subqueryQueryDSL 中的路径引用连接到子查询
【发布时间】:2015-05-29 21:37:57
【问题描述】:

我想知道在连接到子查询的 SQL 样式 QueryDSL 中实现此查询的最佳方式。我有点挣扎,但让它生成了必要的 SQL。但是,我想知道是否有任何简化/改进,特别是与我必须创建的三个“路径”相关?例如,可以根据 latestSubQuery 定义 latestCaseId。

在下面我实际查询的简化形式中,我找到了每个案例组具有最新时间戳的记录集(分布在 ucmpcm 中的字段)。子查询标识每个组的最新时间戳,以便我们可以通过它过滤外部查询。

  final SimplePath<ListSubQuery> latestSubQueryPath = Expressions.path(ListSubQuery.class, "latest");
  final SimplePath<Timestamp> caseLatestMentioned = Expressions.path(Timestamp.class, "caseLatestMentioned");
  final SimplePath<Integer> latestCaseId = Expressions.path(Integer.class, "latest.caseId");

  final ListSubQuery<Tuple> latest = new SQLSubQuery()
          .from(ucm2)
          .innerJoin(pcm2).on(ucm2.id.eq(pcm2.id))
          .groupBy(pcm2.caseId)
          .list(pcm2.caseId.as(latestCaseId), ucm2.lastExtracted.max().as(caseLatestMentioned));

  q.from(ucm)
          .join(pcm).on(ucm.id.eq(pcm.id))
          .innerJoin(latest, latestSubQueryPath).on(pcm.caseId.eq(latestCaseId))
          .where(ucm.lastExtracted.eq(caseLatestMentioned));

【问题讨论】:

    标签: sql orm querydsl


    【解决方案1】:

    我相信你可以使用PathBuilder.get(&lt;various Path impls&gt;) 方法。我想的方式是创建final PathBuilder&lt;Tuple&gt; latestSubQueryPath = new PathBuilder&lt;&gt;(Tuple.class, "latest") 并加入它.innerJoin(latest, latestSubQueryPath) 正在为子查询创建别名。然后您可以使用.get(&lt;various Path impls&gt;) 访问字段,如下所示:

      q.from(ucm)
              .join(pcm).on(ucm.id.eq(pcm.id))
              .innerJoin(latest, latestSubQueryPath).on(pcm.caseId.eq(latestSubQueryPath.get(pcm2.caseId)))
              .where(ucm.lastExtracted.eq(latestSubQueryPath.get(maxLastExtractedDate)));
    

    我没有运行代码,但希望这是正确的方向。如果没有,我明天手头有相关代码库时再看看。

    更新:如 cmets 中所述,ucm2.lastExtracted.max() 需要别名。我称它为 maxLastExtractedDate 并假设它在创建子查询时用于别名 ucm2.lastExtracted.max()

    【讨论】:

    • 这非常有帮助,除了ucm2.lastExtracted.max() 部分外,一切正常。也没有将.max() 移到这些括号之外;这似乎需要一个明确的别名?
    • 我在回复的时候也是这么想的。正如您所说,别名将解决问题。我不相信有更清洁的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    相关资源
    最近更新 更多