Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort list with criteria in hibernate

I am new to Spring3 and Hibernate the following code works great but I am trying to find a way to have my list returned in sort order by the date field. Can someone please show me how to add sort to this code

// To get list of all articles
@SuppressWarnings("unchecked")
public List<Friend> listFriends(String rUser) 
{
   Friend friend = new Friend();
    friend.setUsername(rUser);

    return (List<Friend>) sessionFactory.getCurrentSession()
       .createCriteria(Friend.class)
        .add(Example.create(friend))
        .list();
}
like image 362
Java Review Avatar asked Apr 02 '11 13:04

Java Review


People also ask

How to sort in Hibernate Criteria?

Setting the Sorting Order. The Order class has two methods to set the sorting order: asc(String attribute) : Sorts the query by attribute in ascending order. desc(String attribute) : Sorts the query by attribute in descending order.

How to sort using Criteria?

By default, rows are sorted in ascending order. For example, to sort rows from the ORDERS table by customer ID values, specify 1 for Level and A for Asc/Desc for the CUST_ID column, as shown in the following figure. Once you specify the sort criteria, press ENTER or use END.

Which is sorted in normal order in hibernate?

In hibernate a sorted collection is sorted in memory being Java the responsible of sorting data using compareTo method. Obviously this method is not the best performance-way to sort a collection of elements.


1 Answers

.addOrder( Order.desc("date") )

Check the examples in the documentation

like image 118
Bozho Avatar answered Sep 28 '22 08:09

Bozho