简体   繁体   中英

Spring Data: Order by nested property

I'm using JpaRepository and JpaSpecificationExecutor from Spring Data and i'm having a problem to sort the method findAll(specification, pageable, sort)

I want to sort the result of a specification by a nested property from the main repo class. This is my case:

the main class

class Foo {
    //other properties
    @OneToMany(mappedBy="foo")
    private Set<Bar> bars;
}

the ordering class

class Bar {
    @ManyToOne
    @JoinColumn(name="fooId")
    private Foo foo;

    //I WANT TO SORT BY THIS FIELD
    @Column
    private Date date;
}

and this is my repo

interface FooRepo extends JpaRepository<Foo , Long>, 
        JpaSpecificationExecutor<Foo>{
    //just jparepo methods
}

this is how i'm trying order this result

void anymethod(){
    Sort sort = new Sort(Bar_.date.getName());
    PageRequest pr = new PageRequest(anyPage, anyMaxResultsNum, sort);
    repository.findAll(anySpecification, pr);

}

and when i run this i'm getting the "PropertyReferenceException: No property date found for type Foo!"

How can i do this?

You could use the @javax.persistence.OrderBy annotation:

@OneToMany(mappedBy="foo")
@OrderBy("date")
private Set<Bar> bars;

The date field is defined on Bar , not Foo . So define a BarRepo and call findAll() on the BarRepo using the date sort. Since you have a bi-directional association, you can get Foo from each Bar returned by findAll() and filter out any duplicate Foo .

Or you can try using @Query annotation on a FooRepo interface method to define native sql to execute .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM