2013-07-12 99 views
0

Hibernate用於實現JPA的getResultList()的排序機制是什麼?它是由id還是不能保證一個正確的順序?在JPA javadoc中我沒有看到任何細節。getResultList()的默認排序順序hibernate

/** 
    * Execute a SELECT query and return the query results 
    * as an untyped List. 
    * 
    * @return a list of the results 
    * 
    * @throws IllegalStateException if called for a Java 
    * Persistence query language UPDATE or DELETE statement 
    * @throws QueryTimeoutException if the query execution exceeds 
    * the query timeout value set and only the statement is 
    * rolled back 
    * @throws TransactionRequiredException if a lock mode has 
    * been set and there is no transaction 
    * @throws PessimisticLockException if pessimistic locking 
    * fails and the transaction is rolled back 
    * @throws LockTimeoutException if pessimistic locking 
    * fails and only the statement is rolled back 
    * @throws PersistenceException if the query execution exceeds 
    * the query timeout value set and the transaction 
    * is rolled back 
    */ 
    List getResultList(); 

但每次我運行和測試結果一次給我的ID排序列表。這是我仍然困惑,雖然天才已經投下了這個問題

我只是把show_sql爲真,並檢查生成的SQL。它沒有包括任何排序。

回答

3

這是數據庫返回的元素的順序。

由於數據庫可以任意順序返回ResultSet(特別是在表中插入和刪除時),因此您永遠不會知道它的順序。

爲了確保一定的順序,你必須自己定義這個。

+1

指定的順序是的,我也覺得你是正確的。但是,當我測試我總是得到這些結果通過編號的順序排列:O型 –

+0

@SanjayaLiyanage你可能已經插入上升ID的所有數據。那麼新表按它的順序返回是很自然的,但正如我所說你不能指望這一點。 –

+1

那麼我們插入數據的順序也是如Chase所認爲的?對不起,我問這些事情,以確保答案 –

3

方法getResultList來自javax.persistence.Query返回數據庫返回的默認順序。但是,您可以查詢

List customerList = em.createQuery("SELECT r FROM Customer r").getResultList(); 
    List customerList1 = em.createQuery("SELECT r FROM Customer r order by r.lastUpdatedDate").getResultList(); 
    List customerList2 = em.createQuery("SELECT r FROM Customer r order by r.lastUpdatedDate desc").getResultList();