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