使用spring数据进行不区分大小写的排序

时间:2013-04-03 02:02:04

标签: spring-data-jpa

如何使用Spring-data Pageable进行不区分大小写的排序?

我在我的存储库中有这个方法

public interface ItemRepository extends QueryDslPredicateExecutor<Item>{
    @Query("SELECT o FROM Item o WHERE o.status = ?1")
    Page<Item> findByStatus(Item.Status status, Pageable pageable);
}

我希望能够通过以下方式调用它:

itemRepository.findByStatus(Status.completed, new PageRequest(0, 10, Direction.ASC, "lower(name)")

请注意属性字符串中的lower函数。这不起作用,因为Spring-data期望那里有一个属性。这将转化为:

SELECT o FROM Item o WHERE o.status = ?1 ORDER BY o.lower(name)

当然不会起作用,因为对象上没有'lower'属性。

有没有办法让这项工作?

2 个答案:

答案 0 :(得分:16)

Sort.Order.ignoreCase()大约8个月前推出了spring-data-jpa,请看这里:

https://jira.springsource.org/browse/DATAJPA-296

https://github.com/kraymondksc/spring-data-jpa/commit/c3adce0bd36799d3754a5f4c61aee64982abd7e0

一旦你有了一个合适的spring-data-jpa版本(我认为自1.4 M1以来我有1.4.1)你可以这样写:

Sort.Order order = new Sort.Order(Sort.Direction.ASC, "name").ignoreCase();
itemRepository.findByStatus(Status.completed, new PageRequest(0, 10, new Sort(order));

答案 1 :(得分:0)

以下是我将用于排序的代码:

db.getCollection('employee').aggregate([
  {
    $project: {
         fieldToSortWith: { $toLower: "$lastName" },
         subject: 1
             }
 },
{
    $sort: { fieldToSortWith: 1 },
}
])

这是你在spring数据中的方法

DBCollection coll = mongoTemplate.getCollection("employee");
       List<DBObject> pipe = new ArrayList<>();
        DBObject prjflds = new BasicDBObject();
        prjflds.put("id", 1);
        prjflds.put("firstName", 2);
        prjflds.put("lastName", new BasicDBObject("$toLower", "$lastName"));
        DBObject project = new BasicDBObject();
        project.put("$project", prjflds);
        pipe.add(project);
        DBObject sort = new BasicDBObject();
        sort.put("$sort", new BasicDBObject("lastName", 1));
        pipe.add(sort);
        BasicDBObject skip = new BasicDBObject("$skip", searchCriteria.getCurrentPage() * searchCriteria.getPageSize());
        BasicDBObject limit = new BasicDBObject("$limit", searchCriteria.getPageSize());
        pipe.add(skip);
        pipe.add(limit);
        BasicDBObject employeeRoleFilter = new BasicDBObject("$match", new BasicDBObject("employeeRoles", new BasicDBObject("$in", searchCriteria.getEmployeeRolesNames())));
        pipe.add(employeeRoleFilter);
        BasicDBObject employeeStatusFilter = new BasicDBObject("$match", new BasicDBObject("active", new BasicDBObject("$eq", Boolean.valueOf(searchCriteria.getEmployeeStatus()))));
        pipe.add(employeeStatusFilter);
        searchCriteria.isEmployeeNameSearchIndicator());
        pipe.add(searchTextFilter);
        coll.aggregate(pipe).results();

之后,您将获得需要在域中转换的本机BasicDBObjects。如果您需要任何帮助,请输入此代码。