簡體   English   中英

Spring Data JPA - 是否可以對計算屬性進行排序?

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

假設您有以下實體:

@Entity
public class Game {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    private Calendar startTime;
    private int durationInSeconds;

    public GameStatus getStatus() {
        if( startTime.after(Calendar.getInstance()))
        {
            return GameStatus.SCHEDULED;
        } else {
            Calendar endTime = Calendar.getInstance();
            endTime.setTime(startTime.getTime());
            endTime.roll(Calendar.SECOND, durationInSeconds);

            if( endTime.after(Calendar.getInstance())) {
                return GameStatus.OPEN_FOR_PLAY;
            }
            else {
                return GameStatus.FINISHED;
            }
        }
    }
}

如果我的GameRepositoryPagingAndSortingRepository ,我如何獲得按status屬性排序的結果頁面?

我目前得到:

java.lang.IllegalArgumentException: Unable to locate Attribute  with the the 
given name [status] on this ManagedType [org.test.model.Game]

我可以理解,因為status確實沒有 JPA 屬性。 有沒有辦法解決這個問題?

(我在下面使用 Hibernate,所以任何 Hibernate 特定的東西也可以)

問題是 Spring Data 的 PageRequest 排序是通過形成 ORDER BY 子句在數據庫層完成的。

您可以創建一個@Formula 列,例如

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

然后可以按排序順序使用新列,因為您在公式中編寫的所有內容都將傳遞給 ORDER BY 子句。

使用注解@Formula

示例:ticketPrice = totalAmount / 入場人數

@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;
}

按此列排序需要作為列結果存在。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM