Spring Data JPA - Is it possible to sort on a calculated property?

前端 未结 2 1065
旧巷少年郎
旧巷少年郎 2020-12-19 09:23

Suppose you have the following Entity:

@Entity
public class Game {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    privat         


        
2条回答
  •  有刺的猬
    2020-12-19 09:46

    Use annotation @Formula

    Example: tickePrice = totalAmount / admissions

    @Entity
    public class Event {
    ...
       // To avoid division by 0, and setting to 0 if admissions is 0 
       @Formula(value = "coalesce(totalAmount / NULLIF(admissions, 0), 0)")
       private Double ticketPrice;
    }
    

    To sort by this column is required to be present as a column result.

    GET example-url?size=25&page=0&sort=ticketPrice,ASC
    

提交回复
热议问题