spring数据按嵌套对象列表属性排序

时间:2017-08-03 16:07:16

标签: spring spring-data spring-data-jpa

Spring数据:我正在使用PageRequest进行排序。排序是动态的

String orderByColumn="name"
PageRequest pageRequest = new PageRequest(offset, pageSize, Sort.Direction.ASC, orderByColumn);

Use object包含用户

中的地址列表
private List<Address> addresses

在地址中有属性city

我想对城市使用相同的种类。

我试过orderByColumn="addresses.city" 但它不起作用

有什么线索吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

在您域中的@OrderBy添加List<Address>注释。

@OneToMany(...)
@OrderBy("city")
private List<Address> addresses;

修改

可以根据城市单一查询获得ASC和DESC订购地址。首先,您需要在这样的地址上注释@OrderBy("city DESC")

@OneToMany(...)
@OrderBy("city DESC")
private List<Address> addresses;

之后你需要像这样创建2个getter:

    // this simply get address which is in descending order
    public List<Address> getAddressesWithCitiesSortedInDesc() {
        return addresses;
    }

    // this will make descending ordered address to ascending order
    public List<Address> getAddressesWithCitiesSortedInAsc() {
        Collections.sort(addresses, new Comparator<Address>(){
             public int compare(Address a1, Address a2){
                 return a1.getCity().compareTo(a2.getCity());
             }
        });
        return addresses;
    }

如果你打电话给findAll()方法,你会得到两个像这样的用户的JSON:

   "addressesWithCitiesSortedInAsc": [
              {..},
              {..}
            ],
   "addressesWithCitiesSortedInDesc": [
              {..},
              {..}
            ]