![](/img/trans.png)
[英]How to use ScrollableResults for Hibernate Queries when joining many different entities
[英]Hibernate: how do I retrieve my entities from a ScrollableResults?
我做一個返回實體列表的查詢。 如何從ScrollableResults
檢索實體:
Session s = ....;
Query q = s.createQuery("....") # returns 100000s rows
ScrollableResults sr = q.scroll();
sr.scroll(45999); # just a number
Employee employee = ???
如何在最后一行代碼中獲得員工
嘗試get(0)
方法,或get()[0]
這是API的鏈接: ScrollableResults
get()
返回整個當前行, get(index)
返回index
位置的對象而不初始化其余行。 還有一堆方便的getXXX()方法將結果轉換為給定的類型。
只是為了改進其他答案, ScrollableResults
會為您進行實體轉換,盡管Javadocs並未立即明確這一點。
正如@Bozho所說,調用sr.get()
將返回當前位置的實體,但包含在數組中。 在查看ScrollableResultsImpl
的代碼時,當前行的結果設置為:
if ( result != null && result.getClass().isArray() ) {
currentRow = (Object[]) result;
} else {
currentRow = new Object[] { result };
}
所以ScrollableResults.get()
總是返回一個結果數組,如果你的實體不是一個數組,它將在get()[0]
。
因此,使用您的代碼,您可以執行以下操作:
while (sr.next()) {
// get the entity which is the first element in an Object[]
Employee employee = sr.get()[0];
...
}
要檢索實體,最簡單的方法是將對象轉換為您想要的任何對象:例如:
ScrollableResults sr = q.scroll();
while (sr.next()) {
CustomObject object = (CustomObject) sr.get()[0]; // Now CustomObject will have all the properties mapped
}
這適用於所有場景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.