DATACMNS-59 - AbstractQueryCreator now handles static and dynamic sorting combined.

Added and(…) method to Sort to combine two Sort instances and produce a resulting Sort.
This commit is contained in:
Oliver Gierke
2011-08-16 08:39:25 +02:00
parent ba3cbe7244
commit 1ee347cf40
3 changed files with 44 additions and 6 deletions

View File

@@ -112,6 +112,27 @@ public class Sort implements
}
}
/**
* Returns a new {@link Sort} consisting of the {@link Order}s of the current {@link Sort} combined with the given
* ones.
*
* @param sort can be {@literal null}.
* @return
*/
public Sort and(Sort sort) {
if (sort == null) {
return this;
}
ArrayList<Order> these = new ArrayList<Order>(this.orders);
for (Order order : sort) {
these.add(order);
}
return new Sort(these);
}
/**
* Returns the order registered for the given property.

View File

@@ -80,10 +80,12 @@ public abstract class AbstractQueryCreator<T, S> {
* @param sort
* @return
*/
public T createQuery(Sort sort) {
Sort sortToUse = sort != null ? sort : tree.getSort();
return complete(createCriteria(tree), sortToUse);
public T createQuery(Sort dynamicSort) {
Sort staticSort = tree.getSort();
Sort sort = staticSort != null ? staticSort.and(dynamicSort) : dynamicSort;
return complete(createCriteria(tree), sort);
}
/**
@@ -144,8 +146,8 @@ public abstract class AbstractQueryCreator<T, S> {
/**
* Actually creates the query object applying the given criteria object and {@link Sort} definition.
*
* @param criteria
* @param sort
* @param criteria will never be {@literal null}.
* @param sort might be {@literal null}.
* @return
*/
protected abstract T complete(S criteria, Sort sort);

View File

@@ -16,6 +16,7 @@
package org.springframework.data.domain;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
@@ -92,4 +93,18 @@ public class SortUnitTests {
new Sort(Direction.ASC);
}
@Test
public void allowsCombiningSorts() {
Sort sort = new Sort("foo").and(new Sort("bar"));
assertThat(sort, hasItems(new Sort.Order("foo"), new Sort.Order("bar")));
}
@Test
public void handlesAdditionalNullSort() {
Sort sort = new Sort("foo").and(null);
assertThat(sort, hasItem(new Sort.Order("foo")));
}
}