简体   繁体   中英

ORDER BY Not Working in JPQL Query

I have the following method that returns a HashMap based on a Users Department and Building. I want to ORDER BY ASC based on the user name

private HashMap<Long, String> getCriticalPde(long departmentId, long buildingId) {
    HashMap<Long, String> map = new HashMap<Long, String>();
    Query query = emf
        .createEntityManager()
        .createQuery(
            "SELECT parent FROM Table1 parent WHERE parent.id NOT IN "
            + "(SELECT chldQry.userId FROM Table2 chldQry "
            + "WHERE chldQry.departmentId = :departmentId "
            + "AND chldQry.buildingId = :buildingId)"
            + "ORDER BY parent.userName ASC");
        query.setParameter("departmentId", departmentId);
        query.setParameter("buildingId", buildingId);
        List<User> list= (List <User>) query.getResultList();
        for (User user : userList) {
            map .put(user.getId(), user.getName());
        }
    return map;
}

However when my map is returned it remains ordered by UserId. This script does ORODER BY correctly when ran in Toad/Squirrel/etc. Any ideas?

You are loosing the order because you are using a HashMap, which does not guaratee the order of iteration. Try using a LinkedHashMap instead, it will preserve the original order.

The order by definately works, what doesn't is the HashMap . Hashmaps don't preserve insert order. Use a LinkedHashMap instead

You are retrieving an ordered resultlist and then storing in in an UNordered hashmap. Use an ordered collection to store the users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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