【问题标题】:Custom parameter for sorting passed into URL using ORDER BY用于排序的自定义参数使用 ORDER BY 传递到 URL
【发布时间】:2020-10-04 19:11:14
【问题描述】:

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

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

【问题讨论】:

    标签: java sql jpql


    【解决方案1】:

    这行看起来不对:

    AND su.schoolId = s.id
    

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

    【讨论】:

    • 对不起,这是我的一个。没抄对。它应该是 P,而不是 su。立即修复。
    【解决方案2】:

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

    Pageable pageable =  PageRequest.of(0, limit, Sort.by("fieldName"));
    
    Page<DePerson> newPage = repository.findAll(pageable);
    

    参考文献

    1. 您可以查看article 上的最后一个示例
    2. 另外this是官方文档

    Furthermore如果你想检索班级和学校,那么你可以在你的 DePerson 班级中有一个 ManyToOne 或 OneToOne 关系,并且可以在你的 DePerson 对象中自动加载所有这些,不需要在 Query 和 where 类中分别定义这些类。通过INNER Join,您将需要使用它来组合来自多个表/实体的记录

    否则还有另一个DTO类投影的概念,比如this

    在本文的上下文中,您可以按如下方式添加订单

    // 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();
    

    【讨论】:

    • 谢谢你,但说我无法使用排序方法,这就是为什么我正在寻找方法排序。
    • 要用于排序的 DePerson 类中的字段名称是什么?
    • 您想将三个实体中的数据检索到一个对象中吗?
    • 您好!是的,我认为我们是一致的。您会看到我也希望从其他域类中访问名称,这就是我考虑在查询中使用 ORDER BY 的原因。使用排序方式时,我只能访问 DePerson 的值,但我想访问其他人的信息,有什么建议吗?
    • 请看我回答中的最后一条建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 2016-11-14
    • 2015-11-05
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多