Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
pablobaldez Avatar asked Apr 17 '15 13:04

pablobaldez


People also ask

How do you Sort data in spring?

One option is to use Spring Data's method derivation, whereby the query is generated from the method name and signature. All we need to do here to sort our data is include the keyword OrderBy in our method name, along with the property name(s) and direction (Asc or Desc) by which we want to sort.

Which of the following options can be used for sorting in Spring data JPA?

In Spring Data JPA query results can be sorted in two ways: using an ORDER BY clause in a JPQL query. adding a parameter of type Sort to the query method.

How do I Sort by date in JPA repository?

Data JPA provides Sorting support out of the box. To add Sorting support to our Repositories, we need to extend the PagingAndSortingRepository<T, ID> interface rather than the basic CrudRepository<T, ID> interface. List<Laptop> findAll(Sort sort); Returns a sorted list of laptops.


1 Answers

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

@OneToMany(mappedBy="foo")
@OrderBy("date")
private Set<Bar> bars;
like image 196
sp00m Avatar answered Oct 08 '22 01:10

sp00m