Bulk reading of data in hibernate using scrollable result set

只谈情不闲聊 提交于 2019-12-06 09:19:13

I referred Hibernate API documentation to understand the difference between list() and scroll(). ScrollableResults is like a cursor . An important feature of ScrollableResults is that it allows accessing ith object in the current row of results, without initializing any other results in the row through get(int i) function. It also allows moving back and forth the result set using next() and previous() function.

Example :

  ScrollableResults sc = session.createQuery("select e.employeeName,e.employeeDept FROM Employee e").scroll(ScrollMode.SCROLL_INSENSITIVE);
      while(sc.next()) {
         String empName = (String)sc.get(0);
         System.out.println(empName);
         String empdept = (String)sc.get(1);
         System.out.println(empdept);
      }

The output of above programm will values of employeeName and employeeDept .

Now suppose you want to get the last record of the resultSet. With list() you would need to iterate the whole result. With ScrollableResults, you can use last() function.

Note that for ScrollableResults sc = session.createCriteria(Employee.class).scroll(); should be iterated as

 while(sc.next()) {
     Employee emp = (Employee)sc.get(0);
     System.out.println(emp.getname);
 }

The above code seems to be missing some settings.

Query query = session.createQuery(query);
query.setReadOnly(true);
// MIN_VALUE gives hint to JDBC driver to stream results
query.setFetchSize(Integer.MIN_VALUE);
ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
// iterate over results
while (results.next()) {
    Object row = results.get();
    // process row then release reference
    // you may need to flush() as well
}
results.close();

Follow this link for more details and explanation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!