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

如何在Spring JPA Hibernate中结合分页与排序实现嵌套字段正确排序?

根据子实体age字段对父实体排序的异常问题

简化版实体类

@Entity
class Parent {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "parentId")
    @OnDelete(action = OnDeleteAction.CASCADE)
    @Builder.Default
    @ToString.Exclude
    private List<Child> children = new ArrayList<>();
}

@Entity
class Child {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @Column(nullable = false)
    private Long parentId;

    @Column(nullable = false)
    private String age;
}

问题描述

我正在使用Specification Builder实现查询排序,Child类包含多个字段,除了测试用的age字段外,其他字段的排序逻辑都能正常工作。

当尝试根据Child的age字段对Parent进行排序时,若某个Parent拥有年龄不同的Child,就无法得到预期结果。示例数据如下:

Parent1 = [
Child{
   age: 12
}
Child{
   age: 12
}
Child{
   age: 12
}

],
Parent2 = [
Child{
   age: 5
}
Child{
   age: 5
}
Child{
   age: 5
}
],
Parent3 = [
Child{
   age: 20
}
Child{
   age: 20
}
Child{
   age: 10
}
]

实际排序结果为 parent2、parent1、parent3,但我的预期是 parent2、parent3、parent1——因为Parent3存在age为10的Child,应该排在所有Child age都是12的Parent1之前。

我曾怀疑是age字段为String类型导致的问题,尝试添加了如下转换字段:

@Formula(value = "ABS(age)")
private Integer age;

但结果仍然没有改变。

请问有没有可行的解决思路?

内容的提问来源于stack exchange,提问作者Aleksandar Grujic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:07:35