如何按Spring Data JPA中匹配条件的子实体进行排序

问题描述 投票:0回答:1

我在 Spring Boot 中有两个实体。这是一个可以被任何

Record
“描述”的
RecordProperty

@Entity
public class Record {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private boolean active = false;
    
    private RecordType type;
    
    private String title;

    @OneToMany
    private List<RecordProperty> properties;
    
}

@Entity
public class RecordProperty {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String propertyName;

    private String value;
}

我得到它们如下:

Page<Record> findAll(Pageable pageable);

这是我使用

JPA
Pageable

获得的此类对象的示例列表
{
    "content": [
        {
            "id": 1,
            "active": true,
            "type": "Manual",
            "title": "Some title",
            "properties": [
                {
                    "id": 1,
                    "propertyName": "Foo",
                    "value": "121"
                },
                {
                    "id": 2,
                    "propertyName": "Bar",
                    "value": "1122"
                }
            ],

        },
        {
            "id": 1,
            "active": true,
            "type": "Auto",
            "title": "Some another title",
            "properties": [
                {
                    "id": 1,
                    "propertyName": "Foo",
                    "value": "999"
                },
                {
                    "id": 2,
                    "propertyName": "Bar",
                    "value": "0"
                }
            ]
        }
    ],
    "numberOfItems": 2,
    "numberOfPages": 1
}

记录列表显示在前端的表格中。此外,所有属性都转换为列。所以

property.propertyName
变成了一个柱子,而
property.value
变成了一个单元格。如下:

id 活跃 类型 标题 酒吧
1 真实 手册 一些标题 121 1122
2 真实 自动 另一个标题 999 0

当我在

Sort
Pageable
id
active
列上使用
type
title
时,它显然有效。但是,如何按动态且每次都不同的属性值进行排序呢?我需要首先过滤匹配 propertyName 的记录(例如
Foo
),然后按
Foo
的值排序。但怎样才能做到呢?

spring spring-boot spring-data-jpa spring-data
1个回答
0
投票

您可以像这样对关系属性进行排序:

@OrderBy("value")
@OneToMany
private List<RecordProperty> properties;

这将对单个

properties
内的值进行排序。如果您想对所有
properties
进行排序,那么您需要在获得列表后执行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.