简体   繁体   中英

OrderBy not working while trying to sort by a nested field in JPA Spring Boot

I have entities like this

@Entity
@Table(name = "past_price")
public class PastPrice {

    @Id
    private String symbol;
    @OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    @JoinColumn(name = "symbol")
    private Set<Price> prices = null;

    public String getSymbol() {
        return symbol;
    }

    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }

    public Set<Price> getPrices() {
        return prices;
    }

    public void setPrices(Set<Price> prices) {
        this.prices = prices;
    }

}
@Entity
public class Price {
    @Id
    @Temporal(TemporalType.TIMESTAMP)
    private Date date;
    private String price;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

}

Then I have a JPA repository like this

@Repository
public interface PastPriceRepo extends JpaRepository<PastPrice,String> {
    PastPrice findBySymbol_OrderByPricesDate(String symbol);
}

Where I am trying to sort it by the date that is inside Price class which is inside PastPrice class. But I am not getting the sorted list. I am getting this while calling it from a restcontroller.

{
    "symbol": "SAX",
    "prices": [
        {
            "date": 1552295163000,
            "price": "234.00"
        },
        {
            "date": 1552459623000,
            "price": "236.00"
        },
        {
            "date": 1552470475000,
            "price": "232.00"
        },
        {
            "date": 1553155398000,
            "price": "233.00"
        },
        {
            "date": 1553762003000,
            "price": "234.00"
        },
        {
            "date": 1552469784000,
            "price": "233.00"
        },
        {
            "date": 1553755597000,
            "price": "235.00"
        },
        {
            "date": 1553760225000,
            "price": "234.00"
        },
        {
            "date": 1552284839000,
            "price": "226.00"
        }
    ]
}

How am I supposed to compose my method in the Repository interface? Any help would be appreciated. Thanks

You could do something like

@Repository
public interface PastPriceRepo extends JpaRepository<PastPrice,String> {
    @Query(
        value = "select pp from PastPrice pp join pp.prices ps where pp.symbol=:symbol Order By ps.date desc"
    )
    PastPrice findBySymbol_OrderByPricesDate(@Param("symbol") String symbol);
}

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