我有一个使用 Spring Boot 1.5.1 和 Spring Data Rest 的数据库服务。我将我的实体存储在 MySQL 数据库中,并使用 Spring 的 PagingAndSortingRepository 通过 REST 访问它们。我找到了 this其中声明支持按嵌套参数排序,但我找不到按嵌套字段排序的方法。
我有这些类(class):
@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=name.lastName 和 sort=nameLastName 参数也不起作用。
我形成的 Rest 请求是错误的,还是缺少一些配置?
谢谢!
最佳答案
我发现的解决方法是创建一个额外的只读属性,仅用于排序目的。基于上面的示例:
@Entity(name = "Person")
@Table(name = "PERSON")
public class Person {
// read only, for sorting purposes only
// @JsonIgnore // we can hide it from the clients, if needed
@RestResource(exported=false) // read only so we can map 2 fields to the same database column
@ManyToOne
@JoinColumn(name = "address_id", insertable = false, updatable = false)
private Address address;
// We still want the linkable association created to work as before so we manually override the relation and path
@RestResource(exported=true, rel="address", path="address")
@ManyToOne
private Address addressLink;
...
}
建议的解决方法的缺点是我们现在必须显式复制我们想要支持嵌套排序的所有属性。
后期编辑:另一个缺点是我们无法对客户端隐藏嵌入的属性。在我最初的回答中,我建议我们可以添加 @JsonIgnore,但显然这会破坏排序。
关于Spring Data Rest - 按嵌套属性排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42262846/