Spring Data Rest - 按嵌套属性排序 [英] Spring Data Rest - sort by nested property
问题描述
我有一个使用 Spring Boot 1.5.1 和 Spring Data Rest 的数据库服务.我将我的实体存储在 MySQL 数据库中,并使用 Spring 的 PagingAndSortingRepository 通过 REST 访问它们.我发现 这个 声明支持按嵌套参数排序,但我找不到按嵌套字段排序的方法.
I have a database service using Spring Boot 1.5.1 and Spring Data Rest. I am storing my entities in a MySQL database, and accessing them over REST using Spring's PagingAndSortingRepository. I found this which states that sorting by nested parameters is supported, but I cannot find a way to sort by nested fields.
我有这些课程:
@Entity(name = "Person")
@Table(name = "PERSON")
public class Person {
@ManyToOne
protected Address address;
@ManyToOne(targetEntity = Name.class, cascade = {
CascadeType.ALL
})
@JoinColumn(name = "NAME_PERSON_ID")
protected Name name;
@Id
protected Long id;
// Setter, getters, etc.
}
@Entity(name = "Name")
@Table(name = "NAME")
public class Name{
protected String firstName;
protected String lastName;
@Id
protected Long id;
// Setter, getters, etc.
}
例如使用方法时:
Page<Person> findByAddress_Id(@Param("id") String id, Pageable pageable);
并调用 URI http://localhost:8080/people/search/findByAddress_Id?id=1&sort=name_lastName,desc,Spring完全忽略了sort参数.
And calling the URI http://localhost:8080/people/search/findByAddress_Id?id=1&sort=name_lastName,desc, the sort parameter is completely ignored by Spring.
sort=name.lastName 和 sort=nameLastName 参数也不起作用.
The parameters sort=name.lastName and sort=nameLastName did not work either.
我形成的 Rest 请求是错误的,还是缺少一些配置?
Am I forming the Rest request wrong, or missing some configuration?
谢谢!
推荐答案
我调试了一下,它看起来像 Alan 提到的问题.
I debugged through that and it looks like the issue that Alan mentioned.
我找到了可能有帮助的解决方法:
I found workaround that could help:
创建自己的控制器,注入您的 repo 和可选的投影工厂(如果您需要投影).实现 get 方法以将调用委托给您的存储库
Create own controller, inject your repo and optionally projection factory (if you need projections). Implement get method to delegate call to your repository
@RestController
@RequestMapping("/people")
public class PeopleController {
@Autowired
PersonRepository repository;
//@Autowired
//PagedResourcesAssembler<MyDTO> resourceAssembler;
@GetMapping("/by-address/{addressId}")
public Page<Person> getByAddress(@PathVariable("addressId") Long addressId, Pageable page) {
// spring doesn't spoil your sort here ...
Page<Person> page = repository.findByAddress_Id(addressId, page)
// optionally, apply projection
// to return DTO/specifically loaded Entity objects ...
// return type would be then PagedResources<Resource<MyDTO>>
// return resourceAssembler.toResource(page.map(...))
return page;
}
}
这适用于 2.6.8.RELEASE;这个问题似乎存在于所有版本中.
This works for me with 2.6.8.RELEASE; the issue seems to be in all versions.
这篇关于Spring Data Rest - 按嵌套属性排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!