简体   繁体   中英

Hibernate: how do I retrieve my entities from a ScrollableResults?

I do a query that returns a list of entities. How can I retrieve the entities from a ScrollableResults :

 Session s  = ....;
 Query q = s.createQuery("....") # returns 100000s rows
 ScrollableResults sr = q.scroll();
 sr.scroll(45999); # just a number
 Employee employee = ???

How do I get an employee in the last line of code

尝试get(0)方法,或get()[0]

Here's a link to API: ScrollableResults

get() returns the entire current row, get(index) returns object at index position without initializing the rest of them. There are also a bunch of convenience getXXX() methods that cast result to given type.

Just to improve the other answers, the ScrollableResults does the entity conversion for you although this isn't immediately clear from the Javadocs.

As @Bozho says, calling sr.get() will return the entity at the current location, but wrapped in an array. In looking at the code for ScrollableResultsImpl the current row's result is set with:

    if ( result != null && result.getClass().isArray() ) {
        currentRow = (Object[]) result;
    } else {
        currentRow = new Object[] { result };
    }

So ScrollableResults.get() always returns an array of results and if your entity is not an array, it will be at get()[0] .

So, with your code you would do something like:

while (sr.next()) {
   // get the entity which is the first element in an Object[]
   Employee employee = sr.get()[0];
   ...
}

To retrieve entities the simplest way would be to cast the object to whichever object you want: Eg:

ScrollableResults sr = q.scroll();
while (sr.next()) {
    CustomObject object = (CustomObject) sr.get()[0]; // Now CustomObject will have all the properties mapped
}

This works perfect for all the scenarios.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM