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

前端 未结 2 1066
旧巷少年郎
旧巷少年郎 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
    
    0 讨论(0)
  • 2020-12-19 10:07

    The problem is that Spring Data's PageRequest sort is done on the database layer by forming the ORDER BY clause.

    You could create a @Formula column, e.g.

    @Entity
    public class Game {
    ...
         // rewrite your logic here in HQL
         @Formula("case when startTime >= endTime then 'FINISHED' ... end")
         private String status;
    

    Then it will be possible to use the new column in sort order as everything you write in the formula will be passed to ORDER BY clause.

    0 讨论(0)
提交回复
热议问题