2013-07-12 98 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();