【问题标题】:Pagination in spring-dataspring-data中的分页
【发布时间】:2017-03-24 08:15:10
【问题描述】:

我在使用分页查询数据库时有一个要求。 分页时,我会给查询提供页面大小和页面索引,如下所示,

select distinct tp.* from kat_task_property tp inner join kat_task_to_workstream ttw on ttw.ttw_frn_task_id = tp.tp_frn_task_id and ttw.ttw_frn_workstream_id= :workStreamId and ttw.ttw_ended_by is null and tp.tp_ended_by is null and tp.tp_is_active=true and ttw.ttw_is_active=true left join kat_user_to_task_order kto on ttw.ttw_id = kto.uto_frn_task_to_workstream_id and kto.uto_frn_user_id = :userId order by tp.tp_completed_at ,kto.uto_order limit :index, :size

样本结果将是,

tp_id      tp_completed_at
 1          2017-02-27 06:47:52
 2          null
 3          null
 4           2017-03-14 12:59:24
 5          null
 6          null
 7          null

我的要求是当查询中的索引为 0 时,无论查询中的值大小如何,我都应该获取 tp_completed_at 为空的所有数据。我的意思是,当索引为零时不应该应用分页,我应该得到所有 tp_completed_at 为空的条目。并且,当索引的值不是 0 时,应该应用分页。请帮忙

【问题讨论】:

    标签: java mysql spring-data


    【解决方案1】:

    您可以使用 Pageable 来做到这一点。 PageRequest(页面,大小)

    Pageable page = new PageRequest(0, 10);
    

    例如:

    Page<Incident> findByProblemId(Long problemId, Pageable page);
    

    在你的情况下, countQuery = ".... count(distinct tp.*) ... 无限制"

    @Query(value = "your existing Query without limit ", countQuery = "countQuery", nativeQuery = true)
    getData(@Param("workStreamId") String workStreamId, @Param("userId") String userId, Pageable page);
    

    【讨论】:

    • 我可以在原生查询中使用 Pageable 对象吗
    • @Sandesha 是的,你可以,但你必须像这样定义计数查询 @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1", countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1", nativeQuery = true)
    • 我从未使用过Pageable。如何在我的查询中使用?请帮忙
    • 我希望这会有所帮助:)
    • 我可以在单个查询符号@lucid 中使用两个单独的查询
    【解决方案2】:

    您可以通过根据索引值执行不同的查询来实现这一点。

    编辑:试试这个技巧,如果你的结果集小于 Integer.MAX_VALUE 就可以工作

    @Query("select distinct tp.* from kat_task_property tp inner join kat_task_to_workstream ttw on ttw.ttw_frn_task_id = tp.tp_frn_task_id and ttw.ttw_frn_workstream_id= :workStreamId and ttw.ttw_ended_by is null and tp.tp_ended_by is null and tp.tp_is_active=true and ttw.ttw_is_active=true left join kat_user_to_task_order kto on ttw.ttw_id = kto.uto_frn_task_to_workstream_id and kto.uto_frn_user_id = :userId and order by tp.tp_completed_at, kto.uto_order")
    Page<T> findTp(Pageable pageable);
    
    PagingAndSortingRepository<YourObject, Long> repository = // … get access to a bean
    if(index == 0)
        Page<YourObject> yourObject= repository.findTp(new PageRequest(index, Integer.MAX_VALUE));
    else
        Page<YourObject> yourObject= repository.findTp(new PageRequest(index, size));
    

    【讨论】:

    • 我在第一个查询中向 tp_completed_at 添加了一个 is null 条件,因为您只需要返回那些行
    • 但是我不允许使用两个单独的查询。最多我可以通过 tp_completed_at 来让所有空值彼此相邻
    猜你喜欢
    • 2019-02-22
    • 2013-09-15
    • 1970-01-01
    • 2020-11-29
    • 2021-02-24
    • 2014-01-01
    • 2012-05-25
    • 1970-01-01
    • 2016-02-01
    相关资源
    最近更新 更多