Single fetch with sorted results
I have a code like this.
String[] idList = request.getParameterValues("id");
List list = BookDao.getInstance().getBookList(idList); //select r from Book r where r.id in开发者_如何学Python :idList (using hibernate)
How can I retrieve a list of
list.get(0).getId() == id[0]
and so on
It takes just one line of code to get this done:
Sort the result is using the idList within a Comparator.
// Get the ids as a List so we can use indexOf()
final List<String> ids = Arrays.asList(idList);
// After executing this single line, list will be sorted in idList order:
Collections.sort(list, new Comparator<Book>() {
public int compare(Book o1, Book o2) {
return ids.indexOf(o1.getId()) - ids.indexOf(o2.getId());
}
});
Job done.
If I understand correctly, you would like your book list to be ordered in the same way as your ID array.
The easiest way is not to sort the book list, but to transform it into a map:
Map<String, Book> booksById = new HashMap<String, Book>(list.size());
for (Object o : list) {
Book book = (Book) o;
booksById.put(book.getId(), book);
}
And then, to iterate through your books in the same order as in your ID array, just iterate through this array. Make sure to handle nulls correctly: there could be an ID that doesn't have its corresponding book if it has been deleted:
for (String id : idList) {
Book book = booksById.get(id);
// make sure book is not null
}
Note that you could also simply execute your query, and then re-ask your DAO for each book by ID, since it should be in the session cache anyway:
BookDao.getInstance().getBookList(idList); // queries for books and populate the session cache
for (String id : idList) {
Book book = BookDao.getInstance().getBookById(id); // no additional query since the book is in cache
// make sure book is not null
}
You could sort the fetched listed either in getBookList
or in the code where you are at the moment.
Assuming you want 0-n sorting, first of create a list of strings for the string array, if they are not sorted that is.
Assuming the code:
String[] idList = request.getParameterValues("id");
List<Book> list = BookDao.getInstance().getBookList(idList);
You can do this:
List<String> sortedIds = new ArrayList<String>();
for (String s : idList) {
sortedIds.add(s);
}
Collections.sort(sortedIds);
Now you sort your list of Books:
Collections.sort(books, new Comparator<Book>() {
public int compare(Book book1, Book book2) {
return book1.getId().compareTo(book2.getId());
}
}
Now your lists should be the same in order. Another method is creating a map, but depending on the complexity of your code otherwise, this may or may not be the best solution.
精彩评论