[英]Spring Data - Page Request - order by function
I am trying to implement pagination in Java application based on Spring 4.1.1.RELEASE and Hibernate 4.2.16.Final. 我正在尝试在基于Spring 4.1.1.RELEASE和Hibernate 4.2.16.Final的Java应用程序中实现分页。
I have a following code: 我有以下代码:
PageRequest pageRequest = new PageRequest(pageNumber, pageSize, new Sort(new Order(Direction.DESC, "name"))
Page page = myRepository.findAll(specification, pageRequest);
and everything works fine. 一切正常。 However now I would like to order by sql function value, for example:
ORDER BY CHAR_LENGTH(name)
. 但是,现在我想按sql函数值进行排序,例如:
ORDER BY CHAR_LENGTH(name)
。
It works perfectly when I input such clause in @org.springframework.data.jpa.repository.Query
, for example: 当我在
@org.springframework.data.jpa.repository.Query
输入这样的子句时,它可以完美地工作,例如:
public class MyRepository {
@Query("select e from MyEntity e order by CHAR_LENGTH(e.name)")
public List<MyEntity> findAllOrderedByNameLength();
}
unfortunately I am not able to do it with PageRequest. 不幸的是,我无法使用PageRequest做到这一点。 When I pass:
ORDER BY CHAR_LENGTH(name)
to PageRequest as a property: 当我传递时:
ORDER BY CHAR_LENGTH(name)
作为属性的PageRequest:
PageRequest pageRequest = new PageRequest(pageNumber, pageSize, new Sort(new Order(Direction.DESC, "ORDER BY CHAR_LENGTH(name)"))
Page page = myRepository.findAll(specification, pageRequest);
the following exception is being thrown: 抛出以下异常:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property CHAR found for type MyEntity!
The reason it works in query is that Hibernate passes whatever it doesn't recognize directly into SQL, it isn't a JPA feature so it probably wouldn't work with some other provider. 它在查询中起作用的原因是Hibernate将无法识别的内容直接传递到SQL中,它不是JPA功能,因此它可能无法与其他提供程序一起使用。
One nice option is to implement a custom Order
class, and use that instead. 一个不错的选择是实现自定义
Order
类,而改用它。 You can find detailed instructions in this blog . 您可以在此博客中找到详细说明。 With the exact implementation as in the blog, you would use it as
OrderBySqlFormula.sqlFormula("CHAR_LENGTH(name) desc")
通过与博客中相同的实现,您可以将其用作
OrderBySqlFormula.sqlFormula("CHAR_LENGTH(name) desc")
UPDATE UPDATE
The proposed solution is for Hibernate only, can't be used with Spring Data code, which expects org.springframework.data.domain.Sort.Order
and not org.hibernate.criterion.Order
. 提出的解决方案仅适用于Hibernate,不能与Spring Data代码一起使用,Spring Data代码需要
org.springframework.data.domain.Sort.Order
而不是org.hibernate.criterion.Order
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.