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("....") 开发者_Python百科# 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
try the get(0)
method, or 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.
I do a query that returns a list of entities. How can I retrieve the entities from a ScrollableResults... How do I get an employee.
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: E.g:
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.
精彩评论