我在 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
的值排序。但怎样才能做到呢?
您可以像这样对关系属性进行排序:
@OrderBy("value")
@OneToMany
private List<RecordProperty> properties;
这将对单个
properties
内的值进行排序。如果您想对所有properties
进行排序,那么您需要在获得列表后执行此操作。