0

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。它不包含任何排序。

4

2 回答 2

4

方法getResultListfromjavax.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();
于 2013-07-12T09:39:33.540 回答
3

它是数据库返回的元素的顺序。

您永远不会知道它是哪个顺序,因为数据库可以自由地以ResultSet任何顺序返回 a(尤其是在表中插入和删除时)。

为了确保某个顺序,您必须自己定义它。

于 2013-07-12T07:52:34.137 回答