Hibernate用于实现JPA的getResultList()的排序机制是什么?它是由id还是不保证正确的顺序?我在JPA javadoc中没有看到任何关于此的细节。
/**
* 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设为true并检查生成的sql。它没有任何排序。
答案 0 :(得分:3)
它是数据库返回的元素的顺序。
您永远不会知道它是哪个顺序,因为数据库可以按任意顺序自由返回ResultSet
(特别是在表格中插入和删除时)。
要确保某个订单,您必须自己定义。
答案 1 :(得分:3)
来自getResultList
的方法javax.persistence.Query
返回DB返回的默认顺序。但是,您可以在查询中指定顺序
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();