我有两个实体:Project和ProjectStatus。
项目实体:
@Entity
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@OneToMany(mappedBy = "project")
private List projectStatusses;
}
项目状态实体:
@Entity
public class ProjectStatus {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne
private Project project;
@Enumerated(EnumType.STRING)
private ProjectStatusType statusType;
}
我想按照CriteriaQuery.orderBy的最新状态订购项目。
我想出了以下内容:
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Project.class);
Root root = criteriaQuery.from(Project.class);
Join join = root.join("projectStatusses", JoinType.LEFT);
criteriaQuery.orderBy(criteriaBuilder.asc(join.get("statusType")));
我希望上面的查询只考虑最新的项目状态,但我不知道该怎么做。
我怎样才能做到这一点?
更新:
实现这个的sql是:
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