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

前端 未结 11 1328
说谎
说谎 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条回答
  •  Happy的楠姐
    2020-12-04 17:20

    You can use MultiQuery to execute both queries in a single database call, which is much more efficient. You can also generate the count query, so you don't have to write it each time. Here's the general idea ...

    var hql = "from Item where i.Age > :age"
    var countHql = "select count(*) " + hql;
    
    IMultiQuery multiQuery = _session.CreateMultiQuery()
        .Add(s.CreateQuery(hql)
                .SetInt32("age", 50).SetFirstResult(10))
        .Add(s.CreateQuery(countHql)
                .SetInt32("age", 50));
    
    var results = multiQuery.List();
    var items = (IList) results[0];
    var count = (long)((IList) results[1])[0];
    

    I imagine it would be easy enough to wrap this up into some easy-to-use method so you can have paginateable, countable queries in a single line of code.

    As an alternative, if you're willing to test the work-in-progress Linq for NHibernate in nhcontrib, you might find you can do something like this:

    var itemSpec = (from i in Item where i.Age > age);
    var count = itemSpec.Count();
    var list = itemSpec.Skip(10).Take(10).AsList(); 
    

    Obviously there's no batching going on, so that's not as efficient, but it may still suite your needs?

    Hope this helps!

提交回复
热议问题