【发布时间】:2018-06-03 13:00:47
【问题描述】:
我是 Hibernate 的新手,我正在尝试编写一个条件查询来返回给定日期员工的最新状态
id | Status | status_date
1 | Active | 1/10/2017
2 | Active | 1/10/2017
...
1 | Inactive| 5/10/2017
...
1 | Active | 9/10/2017
所以我将向查询传递一个日期,并希望找到该日期每个员工的最新状态 预期的结果会是这样的
示例:对于日期 6/1/2017,这将是返回的数据
id | Status | Date
1 | Inactive| 5/10/2017
2 | Active | 1/10/2017
我能够通过 id 添加 group by 并按状态日期以降序排列行。有没有办法只为每个组选择第一行?我尝试在 status_date 上使用 max 函数,但不起作用。
CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> cq = builder.createQuery(Employee);
Root<Employee> root = cq.from(Employee.class);
cq.select(root);
cq.groupBy(root.get("id"));
cq.orderBy(builder.desc(root.get("status_date")));
cq.having(builder.max(root.get("status_date")));
【问题讨论】:
-
这个类似的问题可能会有所帮助:stackoverflow.com/questions/8491796/…
标签: java hibernate oracle11g hibernate-criteria