Spring 数据剩余 - 按嵌套排序 属性

Spring Data Rest - sort by nested property

我有一个使用 Spring Boot 1.5.1 和 Spring Data Rest 的数据库服务。我将我的实体存储在 MySQL 数据库中,并使用 Spring 的 PagingAndSortingRepository 通过 REST 访问它们。我发现 this 指出支持按嵌套参数排序,但我找不到按嵌套字段排序的方法。

我有这些 类:

@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.lastNamesort=nameLastName 也不起作用。

我是不是构建了 Rest 请求错误,或者缺少某些配置?

谢谢!

我已经调试过了,它看起来像 Alan 提到的问题。

我找到了可以提供帮助的解决方法:

创建自己的控制器,注入你的 repo 和可选的投影工厂(如果你需要投影)。实施 get 方法以委托对您的存储库的调用

 @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;这个问题似乎存在于所有版本中。

我找到的解决方法是创建一个额外的只读 属性 仅用于排序目的。基于以上示例:

@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 数据 REST 文档:

Sorting by linkable associations (that is, links to top-level resources) is not supported.

https://docs.spring.io/spring-data/rest/docs/current/reference/html/#paging-and-sorting.sorting

我发现的替代方法是使用 @ResResource(exported=false)。 这是无效的(特别是对于遗留 Spring 数据 REST 项目),因为避免加载 resource/entity HTTP 链接:

JacksonBinder
BeanDeserializerBuilder updateBuilder throws
 com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of ' com...' no String-argument constructor/factory method to deserialize from String value

我尝试在 annotations 的帮助下通过可链接关联激活排序但没有成功,因为我们总是需要重写 JacksonMappingAwareSortTranslator.SortTranslatormappPropertyPath 方法来检测注释:

            if (associations.isLinkableAssociation(persistentProperty)) {
                if(!persistentProperty.isAnnotationPresent(SortByLinkableAssociation.class)) {
                    return Collections.emptyList();
                }
            }

注释

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SortByLinkableAssociation {
}

在项目中将关联标记为 @SortByLinkableAssociation:

@ManyToOne
@SortByLinkableAssociation
private Name name;

真的,我没有找到解决这个问题的明确和成功的解决方案,但决定公开它让我们考虑一下,甚至 Spring 团队考虑将其包含在下一个版本中。

当我们想要按链接实体排序时,请参阅 以了解可能的 workaround/hack。