Reputation: 1157
I've got 2 entities: Project and ProjectStatus.
Project Entity:
@Entity
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@OneToMany(mappedBy = "project")
private List<ProjectStatus> projectStatusses;
}
Project Status Entity:
@Entity
public class ProjectStatus {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne
private Project project;
@Enumerated(EnumType.STRING)
private ProjectStatusType statusType;
}
I would like to order projects by their latest status type with CriteriaQuery.orderBy
.
I came up with the following:
CriteriaQuery<Project> criteriaQuery = criteriaBuilder.createQuery(Project.class);
Root<Project> root = criteriaQuery.from(Project.class);
Join<Project, ProjectStatus> join = root.join("projectStatusses", JoinType.LEFT);
criteriaQuery.orderBy(criteriaBuilder.asc(join.get("statusType")));
I want the above query to only take the latest project status into account, but I do not know how to do that. How can I achieve this?
Update: The sql to achieve this is:
SELECT proj.*, stat.statustype
FROM project proj
LEFT JOIN projectStatus stat ON proj.id = stat.project_id
WHERE stat.id = (SELECT MAX(id) FROM projectstatus WHERE project_id = proj.id)
ORDER BY stat.statustype
Upvotes: 3
Views: 4559
Reputation: 1157
I am not a fan of answering my own question, but I found the solution. Hopefully it will help somebody else.
My fault was to look for a solution in the criteriaQuery.orderBy
method. Adding a subquery in the criteriaQuery.where
method did the trick.
Solution:
CriteriaQuery<Project> criteriaQuery = criteriaBuilder.createQuery(Project.class);
Root<Project> root = criteriaQuery.from(Project.class);
Join<Project, ProjectStatus> join = root.join("projectStatusses", JoinType.LEFT);
//Create a subquery to get latest ProjectStatus for project
Subquery sq = criteriaBuilder.createQuery().subquery(Long.class);
Root<T> from = sq.from(Project.class);
Path<ProjectStatus> path = root.join("projectStatusses");
//Get latest status
sq.select(criteriaBuilder.max(path.<Long>get("id")));
//For each project
sq.where(criteriaBuilder.equal(from.<Long>get("id"), root.<Long>get("id")));
Predicate latestStatusCondition = criteriaBuilder.and(criteriaBuilder.equal(join.get("id"), sq));
criteriaQuery.orderBy(criteriaBuilder.asc(join.get("statusType")));
criteriaQuery.where(latestStatusCondition);
Upvotes: 3