Spring Data JPA – 是否可以对计算属性进行排序?

假设您有以下实体:

@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子句。