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 guarantee the order of iteration. Try using a LinkedHashMap instead, it will preserve the original order.