Spring Data Rest - sort by nested property

后端 未结 3 1448
[愿得一人]
[愿得一人] 2021-01-08 00:56

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 PagingAndS

3条回答
  •  -上瘾入骨i
    2021-01-08 01:36

    The workaround I found is to create an extra read-only property for sorting purposes only. Building on the example above:

    @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;
    
        ...
    }
    

    The drawback for the proposed workaround is that we now have to explicitly duplicate all the properties for which we want to support nested sorting.

    LATER EDIT: another drawback is that we cannot hide the embedded property from the clients. In my original answer, I was suggesting we can add @JsonIgnore, but apparently that breaks the sort.

提交回复
热议问题