Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA REST sort by nested property

I have entity Market and Event. Market entity has a column:

@ManyToOne(fetch = FetchType.EAGER)
private Event event;

Next I have a repository:

public interface MarketRepository extends PagingAndSortingRepository<Market, Long> {
}

and a projection:

@Projection(name="expanded", types={Market.class})
public interface ExpandedMarket {
    public String getName();
    public Event getEvent();
}

using REST query /api/markets?projection=expanded&sort=name,asc I get successfully the list of markets with nested event properties ordered by market's name:

{
    "_embedded" : {
        "markets" : [ {
            "name" : "Match Odds",
            "event" : {
                "id" : 1,
                "name" : "Watford vs Crystal Palace"
            },
            ...
        }, {
            "name" : "Match Odds",
            "event" : {
                "id" : 2,
                "name" : "Arsenal vs West Brom",
            },
            ...
        },
        ...
    }
}

But what I need is to get list of markets ordered by event's name, I tried the query /api/markets?projection=expanded&sort=event.name,asc but it didn't work. What should I do to make it work?

like image 462
uiii Avatar asked Jan 23 '17 13:01

uiii


2 Answers

Based on the Spring Data JPA documentation 4.4.3. Property Expressions

... you can use _ inside your method name to manually define traversal points...

You can put the underscore in your REST query as follows:

/api/markets?projection=expanded&sort=event_name,asc

like image 96
Daniel Solomon Avatar answered Sep 28 '22 19:09

Daniel Solomon


Just downgrade spring.data.‌​rest.webmvc to Hopper release

<spring.data.jpa.version>1.10.10.RELEASE</spring.data.jpa.ve‌​rsion> 
<spring.data.‌​rest.webmvc.version>‌​2.5.10.RELEASE</spri‌​ng.data.rest.webmvc.‌​version>

projection=expanded&sort=event.name,asc // works
projection=expanded&sort=event_name,asc // this works too

Thanks @Alan Hay comment on this question

Ordering by nested properties works fine for me in the Hopper release but I did experience the following bug in an RC version of the Ingalls release.bug in an RC version of the Ingalls release. This is reported as being fixed,

  • jira issue - Sorting by an embedded property no longer works in Ingalls RC1

BTW, I tried v3.0.0.M3 that reported that fixed but not working with me.

like image 42
Khaled Lela Avatar answered Sep 28 '22 20:09

Khaled Lela