简体   繁体   English

休眠的getResultList()的默认排序顺序

[英]Default sorting order of getResultList() hibernate

What is the sorting mechanism of Hibernate for implementation of getResultList() of JPA ? Hibernate实现JPA的getResultList()的排序机制是什么? Is it by the id or is it not guaranteed a proper order ? 是通过ID还是不能保证顺序正确? I did not see any detail regarding this in JPA javadoc. 我在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();

But each time I run and test the results it give me the list ordered by id. 但是每次我运行并测试结果时,它都会给我ID排序的列表。 That is what I am still confused although a genius had down voted this problem 那是我仍然感到困惑的,尽管天才已经否决了这个问题。

I just put show_sql true and checked the generated sql. 我只是将show_sql设置为true并检查了生成的sql。 It does not have any sorting included. 它不包含任何排序。

Method getResultList from javax.persistence.Query returns the default order which returned by DB. javax.persistence.Query方法getResultList返回DB返回的默认顺序。 However, you can specify the order in 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();

It's is the order of the elements returned by the database. 这是数据库返回的元素的顺序。

You will never know which order it is as the database is free to return a ResultSet in any order (especially when inserting and deleting in a table). 您将永远不会知道它的顺序,因为数据库可以自由地以任何顺序返回ResultSet (尤其是在表中插入和删除时)。

To ensure a certain order you have to define this yourself. 为了确保一定的顺序,您必须自己定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM