英文:
Spring Data Pageable sort with nested property
问题
在我的Spring Boot应用程序中,我有一个具有嵌入式主键的实体:
```java
public class MyEntity {
@EmbeddedId
private MyPk pk;
}
@Embeddable
public class MyPk implements Serializable {
private Integer key1;
private Integer key2;
}
要使用Spring的Pageable对象对结果进行排序,我必须调用REST服务:localhost?sort=pk.key1,asc
使用JPA,是否可以接受没有pk的请求?例如:localhost?sort=key1,asc
我希望能够在服务级别实现这一点。
<details>
<summary>英文:</summary>
in my Spring boot application I have an entity with an embedded primary key:
```java
public class MyEntity {
@EmbeddedId
private MyPk pk;
}
@Embeddable
public class MyPk implements Serializable {
private Integer key1;
private Integer key2;
}
To sort the results using spring's Pageable object I have to call the rest service at: localhost?sort=pk.key1,asc
Is it possible, using JPA, to accept requests without pk? For example: localhost?sort=key1,asc
I'd like to be able to do this at the service level
答案1
得分: 1
你需要在将它们传递给数据层之前重新编写这些排序部分:
@RequiredArgsConstructor
@Service
public class YourService {
public static final Set<String> NESTED_PK_PROPERTIES = Set.of("key1", "key2");
private final YourRepository repository;
@Transactional(readOnly = true)
public Page<YourResultType> search(final Pageable pageable) {
// 如果排序属性引用嵌套属性,则更正排序
final Sort sort = Sort.by(
pageable.getSort().get()
.map(order -> NESTED_PK_PROPERTIES.contains(order.getProperty()) ?
Sort.Order
.by(String.format("%s_%s", "pk", order.getProperty()))
.with(order.getDirection()) :
order)
.collect(Collectors.toList()));
// 获取与搜索条件匹配的手动更改
return repository.findAll(PageRequest.of(
pageable.getPageNumber(), pageable.getPageSize(), sort));
}
}
英文:
You would have to rewrite the sorts before passing them to the data layer:
@RequiredArgsConstructor
@Service
public class YourService {
public static final Set<String> NESTED_PK_PROPERTIES = Set.of("key1", "key2");
private final YourRepository repository;
@Transactional(readOnly = true)
public Page<YourResultType> search(final Pageable pageable) {
// Correct sort properties if they refer to a nested property
final Sort sort = Sort.by(
pageable.getSort().get()
.map(order -> NESTED_PK_PROPERTIES.contains(order.getProperty()) ?
Sort.Order
.by(String.format("%s_%s", "pk", order.getProperty()))
.with(order.getDirection()) :
order)
.collect(Collectors.toList()));
// Get manual changes matching the search criteria
return repository.findAll(PageRequest.of(
pageable.getPageNumber(), pageable.getPageSize(), sort));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论