I am new to Hibernate and I am trying to write a criteria query to return the latest status of employee on a given date
id | Status | status_date
1 | Active | 1/10/2017
2 | Active | 1/10/2017
...
1 | Inactive| 5/10/2017
...
1 | Active | 9/10/2017
So I will be passing a date to the query and want to find the latest status of every employee on that date The expected result will be something like this
Example: For date 6/1/2017, this will be the returned data
id | Status | Date
1 | Inactive| 5/10/2017
2 | Active | 1/10/2017
I was able to add group by with id and order the rows by status date in descending order. Is there a way I can select only the top row for each group? I tried to use the max function on status_date but that does not work.
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")));