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

示例: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;
}

要按此列排序,必须作为列结果出现。

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