java—自定义参数,用于使用order by对传递到url的内容进行排序

sc4hvdpw  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(306)

我想首先声明,我知道已经有一个排序函数,可以使用以下方法调用它:

http://localhost:8080/api/person?sort=name,ASC

但是,由于我依赖于多个域,所以目前无法使用这种排序类型。因此,我决定创建一个自定义排序参数,如下所示:

http://localhost:8080/api/person?ordering=name

然后我决定查看我的存储库,创建一个自定义jpql,在调用上面的url时,可以使用它对我的值进行排序:
回购方式:

@Query("SELECT p FROM DePerson p, DeClass c, DeSchool s" +
    "WHERE p.personId = c.id " +
    "AND p.schoolId = s.id " +
    "ORDER BY :ordering")
Page<DeSiteUser> orderingAll(@Param("ordering") String ordering, Pageable pageable);

服务方式:

Page<DePerson> newPage = repository.orderingAll(ordering, pageable);

    List<DePerson> personList = newPage.getContent();
    for (DePerson person: personList ) {
        result.add(convertDTO(person));
    }

    return new PageImpl<>(result, pageable, page.getTotalElements());

由此我称之为,现在我得到了一个错误:

There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet

我想问两个问题。1.这是使用order by生成自定义排序参数的正确路径。2.为什么我会出错。谢谢您。

aemubtdh

aemubtdh1#

这条线看起来不对:

AND su.schoolId = s.id

您的请求中没有“su”。你是说c而不是苏?

pu3pd22g

pu3pd22g2#

你需要像下面这样做。不需要在存储库中定义方法。

Pageable pageable =  PageRequest.of(0, limit, Sort.by("fieldName"));

Page<DePerson> newPage = repository.findAll(pageable);

参考文献
您可以查看本文的最后一个示例
这也是官方文件
此外,如果你想检索班级和学校,那么你可以有一个 ManyToOne 或者 OneToOne deperson类中的关系,并且可以自动将所有这些类加载到deperson对象中,无需在查询和where类中分别定义这些类。顺便说一句 INNER Join 用于组合多个表/实体中的记录
否则还有另一个dto类投影的概念
在本文的上下文中,您可以按如下方式添加订单

// Execute query
Order orderByBookTitle = cb.asc(root.get(Book_.title));
// or
Order orderByAuthorFirstName = cb.asc(author.get(Author_.firstName));
cq.orderBy(orderByDeptTitle, orderByAuthorFirstName);
TypedQuery<BookWithAuthorNames> q = em.createQuery(cq);
q.setParameter(paramTitle, "%Hibernate Tips%");
List<BookWithAuthorNames> books = q.getResultList();

相关问题