0

I am working on application using hibernate and spring. I am trying to get count of result got by query by using ScrollableResults but as query contains lots of join(Inner joins), the result contains id repeated many times. this creates problem for ScrollableResults when i am using it to know total no of unique rows(or unique ids) returned from database. please help. Some part of code is below :

        StringBuffer queryBuf = new StringBuffer("Some SQL query with lots of Joins");

        Query query = getSession().createSQLQuery(queryBuf.toString());

        query.setReadOnly(true);


        ScrollableResults results = query.scroll();
        if (results.isLast() == false)
            results.last();
        int total = results.getRowNumber() + 1;

        logger.debug(">>>>>>TOTAL COUNT<<<<<< = {}", total);

It gives total count 1440 but actual unique rows in database is 504. Thanks in Advance.

newProgramer
  • 79
  • 2
  • 5
  • 16

3 Answers3

1

You can try

Integer count= ((Long)query.uniqueResult()).intValue();
Marginean Vlad
  • 329
  • 1
  • 6
  • 1
    I tried the same, but it takes very long. It seems to me that uniqueResult() goes through all the records, in which case I gain nothing from using ScrollableResults... – IntelliData Jun 21 '16 at 15:06
1

getRowNumber() gives the number of the current row. Call last() and afterwards getRowNumber()+1 will give the total number of results.

tgallei
  • 827
  • 3
  • 13
  • 22
Pilso
  • 61
  • 3
0

Unfortunately, getRowNumber does not give you the size, or the number of results, but the current position in the results. ScrollableResults does not provide a way to get the number of results out-of-the-box.

I am referring to ScrollableResults Hibernate Version 5.4.

As a workaround, you can try

Long l_resultsCount = 0L;
while(results.next()) {
    l_resultsCount++;
}