自定义参数,用于使用ORDER BY向URL中传递排序信息。

问题描述 投票:0回答:2

首先我想说明的是,我知道已经有了一个排序函数,而且可以用这个来调用。

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

然而,由于我依赖于多个域,我目前无法使用这种排序类型。由此,我决定做一个自定义的排序参数,所以类似于这样。

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

然后我决定研究我的仓库,创建一个自定义的JPQL,当调用上面的URL时,可以用来对我的值进行排序。

REPO METHOD:

@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);

SERVICE METHOD:

    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. 我为什么会出现这个错误。谢谢你。

java sql jpql
2个回答
0
投票

这一行看起来是错误的。

AND su.schoolId = s.id

在你的请求中没有 "su "这个词. 你的意思是c而不是su吗?


0
投票

你需要像下面这样做。你不需要在版本库中定义一个方法。

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

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

引用

  1. 你可以在这里查看最后一个例子 文章
  2. 另外 这个 是正式文件

另外 如果你想检索班级和学校,那么你可以有一个。ManyToOneOneToOne DePerson类内的关系,并且可以在DePerson对象中自动加载所有这些内容,不需要在Query和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();
© www.soinside.com 2019 - 2024. All rights reserved.