Is there a more efficient way of making pagination in Hibernate than executing select and count queries?

前端 未结 11 1316
说谎
说谎 2020-12-04 16:36

Usually pagination queries look like this. Is there a better way instead of making two almost equal methods, one of which executing \"select *...\" and the other one \"count

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 17:24

    I think the solution depends on database you are using. For example, we are using MS SQL and using next query

    select 
      COUNT(Table.Column) OVER() as TotalRowsCount,
      Table.Column,
      Table.Column2
    from Table ...
    

    That part of query can be changed with database specified SQL.

    Also we set the query max result we are expecting to see, e.g.

    query.setMaxResults(pageNumber * itemsPerPage)
    

    And gets the ScrollableResults instance as result of query execution:

    ScrollableResults result = null;
    try {
        result = query.scroll();
        int totalRowsNumber = result.getInteger(0);
        int from = // calculate the index of row to get for the expected page if any
    
        /*
         * Reading data form page and using Transformers.ALIAS_TO_ENTITY_MAP
         * to make life easier.
         */ 
    }
    finally {
        if (result != null) 
            result.close()
    }
    

提交回复
热议问题