Reputation: 9994
I have a MySQL database includes a table named 'Task'. and I used Hibernate to map the data to the database.
it includes these fields : id, user_id, project_id, deliverable_id, activity_id, ...
When I retrieve Tasks from Db, I need to sort them by Project at first, and then by Deliverable and finally by Activty.
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Task> tasks = (List<Task>)session.createQuery(
"from Task as t where t.user.username = :name order by t.project.key ASC").setString("name", username).list();
orderByDeliverable(tasks);
orderByActivity(tasks);
private void orderByDeliverable(List<Task> tasks) {
Collections.sort(tasks, new Comparator<Task>(){
public int compare(Task t1, Task t2) {
if(t1.getProject().getId() == t2.getProject().getId())
return t1.getDeliverable().getKey().compareToIgnoreCase(t2.getDeliverable().getKey());
return 0;
}
});
}
private void orderByActivity(List<Task> tasks) {
Collections.sort(tasks, new Comparator<Task>(){
public int compare(Task t1, Task t2) {
if(t1.getProject().getId() == t2.getProject().getId())
if(t1.getDeliverable().getId() == t2.getDeliverable().getId())
return t1.getActivity().getKey().compareToIgnoreCase(t2.getActivity().getKey());
return 0;
}
});
}
As you see in the code I used two methods to sort them by deliverable and activity, but I sort them by project in the Query.
I am not good in Query writing, do you know any way that I can do all sorting stuff in the query and get the same result ?
Upvotes: 2
Views: 800
Reputation: 9994
I found the answer. I just need to use this query:
tasks = (List<Task>)session.createQuery("from Task as t where t.user.username = :name
order by t.project.key ASC, t.deliverable.key ASC, t.activity.key ASC")
.setString("name", username).list();
It worked the same for me.
Actually I looked for this solution to speed-up the application that I have developed. I tested that which one is faster. The result was the same. It does not speed-up the application.
Upvotes: 1