Cayenne User Documentation
Using Orderings

To sort SelectQuery results, Orderings are used. Orderings use path expressions discussed in the previous section to identify the attributes that must be used in sorting. Orderings also use a SortOrder to identify how the ordering should be performed.

There are 4 SortOrder options:

- ASCENDING (ascending order, case – or database – sensitive)
- ASCENDING_INSENSITIVE (ascending order, case-insensitive)
- DESCENDING (descending order, case – or database – sensitive)
- DESCENDING_INSENSITIVE (descending order, case-insensitive)

To order results by artist name, the following code can be used:

    import org.apache.cayenne.query.SelectQuery;
    import org.apache.cayenne.query.SortOrder;
    ...
    SelectQuery query = new SelectQuery("Artist");

    // add ordering by Artist name:
    query.addOrdering("artistName", SortOrder.ASCENDING);

| Legacy Information In Cayenne versions prior to 3.0, the addOrdering() call in the above example would appear as `query.addOrdering("artistName", true)`. A boolean parameter of true meant to order ascending (false descending).

Orderings also support in-memory sorting of lists of Java Beans (all DataObjects are normally Java Beans, since they has set/get method pairs for all the properties). For instance to sort with a single ordering, the following code might be used:

    import org.apache.cayenne.query.Ordering;
    import org.apache.cayenne.query.SortOrder;
    ...
    // assume this is a properly initialized list of Artists
    List list = ...;

    // creates asending ordering by Artist name
    Ordering ordering = new Ordering("artistName", SortOrder.ASCENDING);

    // orders a list
    ordering.orderList(list);

| Legacy Information In Cayenne versions prior to 3.0, the Ordering() constructor in the above example would appear as: `new Ordering("artistName", true)`. A boolean parameter of true meant to order ascending (false descending).

If there is a need to sort on more than one object property, multiple Orderings can be passed as a List to a static method `orderList(List, List)`. The cost of adding new Orderings decreases, as the list of objects ends up being sorted by the first Ordering, then, if any two objects are equal for first Ordering, by the second, and so on.

    import org.apache.cayenne.query.Ordering;
    import org.apache.cayenne.query.SortOrder;
    ...
    // assume this is a properly initialized list of Paintings
    List list = ...;

    List orderings = new ArrayList();
    orderings.add(new Ordering("paintingTitle", SortOrder.ASCENDING));
    orderings.add(new Ordering("estimatedPrice", SortOrder.DESCENDING));

    // orders a list aplying multiple orderings
    Ordering.orderList(list, orderings);

.
Copyright ©2001-2010 Apache Software Foundation