You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JPA Specification实现一对多关系中按子实体最大日期排序的问题咨询

JPA Specification实现一对多关系中按子实体最大日期排序的问题咨询

我需要编写一个JPA Specification,用来返回所有Parent实体,并按照Child实体的date字段(LocalDate类型)进行排序。

对应的实体类代码如下:

@Entity
public class Parent {
    @Id
    private UUID id;
    @OneToMany(mappedBy = "parent", cascade = CascadeType.MERGE)
    private List<Child> children = new ArrayList<>();
}


@Entity
public class Child {
    @Id
    private UUID id;
    @ManyToOne
    private Parent parent;
    private LocalDate date;
}

我尝试了下面的实现方式,但它并没有按照预期工作,我也搞不懂原因:

return (root, query, builder) -> {
    Join<Parent, Child> childrenJoin = root.join("children", JoinType.LEFT);

    query.orderBy(sortOrder.equals("asc") ? 
        builder.asc(builder.max(childrenJoin.get("date"))) : 
        builder.desc(builder.max(childrenJoin.get("date"))));

    return builder.conjunction();
};

对应的SQL查询应该是这样的,这个SQL能得到正确的排序结果:

SELECT p.id, max(c.date) FROM schema.parent p
LEFT JOIN schema.child c ON c.parent_id = p.id
GROUP BY p.id
ORDER BY MAX(c.date) DESC;

提前感谢各位的帮助!


编辑补充:
上面的SQL查询能按照正确的顺序(日期升序或降序)对所有记录排序,但使用我提供的Specification调用repository.findAll(specification)时,返回的记录顺序和SQL查询的结果不一致,是错误的顺序。

我想确认的是,这种需求用JPA Specification实现的话,我当前的写法是正确的吗?还是说我漏掉了什么?毕竟SQL和Specification的结果排序不一样,肯定是哪里有问题。

备注:内容来源于stack exchange,提问作者ghosted

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:13:09