【问题标题】:Convert SQL into CriteriaBuilder statement将 SQL 转换为 CriteriaBuilder 语句
【发布时间】:2019-07-03 17:38:30
【问题描述】:

你能帮我把这个 SQL 语句转换成 CriteriaBuilder 语句吗?我遇到的问题是 INNER JOIN 语句。

SELECT th.id, th.date, th.exercise_id
FROM traininghistory th
INNER JOIN (
  SELECT exercise_id, MAX(date) as maxdate
  FROM traininghistory
  group by exercise_id
  ) AS tm on tm.exercise_id = th.exercise_id AND th.date = tm.maxdate
WHERE th.accountid = :accountId

@Entity
public class TrainingHistory {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @NotNull
    public Long id;

    public Long accountId;

    @ManyToOne
    public Exercise exercise;

    public Date dateDone = new Date();

    public WellBeing wellBeing;

    public int weight;

    public int repetitions;

    public int duration;
}

【问题讨论】:

  • 请您发布受影响的实体。没有任何实体是不可能提出任何建议的。

标签: java postgresql jpa


【解决方案1】:

通过重新编写不带INNER JOIN 的查询找到了解决方案。以下 SQL 查询实现了与问题中的 SQL 查询相同的结果,但我可以将其转换为 Criteria API。

FROM traininghistory th
WHERE th.datedone in (
SELECT MAX(tm.datedone)
  FROM traininghistory tm
  GROUP BY tm.exercise_id
)
AND th.accountid = :userId

因此以此为基础,使用 Criteria API 的语句如下:

// define query
CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
CriteriaQuery<TrainingHistory> query = cb.createQuery(TrainingHistory.class);
Root<TrainingHistory> root = query.from(TrainingHistory.class);
query.select(root);

// define subquery
Subquery<Integer> subquery = query.subquery(Integer.class);
Root<TrainingHistory> rootSubquery = subquery.from(TrainingHistory.class);
Expression<Integer> max = cb.max(rootSubquery.get(TrainingHistory_.DATE_DONE));
   subquery.select(max);
   subquery.groupBy(rootSubquery.get(TrainingHistory_.exercise));

// compose whole query
query.where(
   cb.and(
      cb.in(root.get(TrainingHistory_.DATE_DONE)).value(subquery),
      cb.equal(root.get(TrainingHistory_.ACCOUNT_ID), userId)
  )
);

return this.entityManager.createQuery(query).getResultList();

【讨论】:

    猜你喜欢
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2013-02-15
    • 1970-01-01
    • 2023-03-15
    • 2019-09-15
    • 1970-01-01
    相关资源
    最近更新 更多