Skip to content

Commit

Permalink
DATACMNS-59 - AbstractQueryCreator now handles static and dynamic sor…
Browse files Browse the repository at this point in the history
…ting combined.

Added and(…) method to Sort to combine two Sort instances and produce a resulting Sort.
  • Loading branch information
odrotbohm committed Aug 16, 2011
1 parent ba3cbe7 commit 1ee347c
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 6 deletions.
Expand Up @@ -112,6 +112,27 @@ public Sort(Direction direction, List<String> properties) {
}
}

/**
* 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.
Expand Down
Expand Up @@ -80,10 +80,12 @@ public T createQuery() {
* @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);
}

/**
Expand Down Expand Up @@ -144,8 +146,8 @@ private S createCriteria(PartTree tree) {
/**
* 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);
Expand Down
Expand Up @@ -16,6 +16,7 @@

package org.springframework.data.domain;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.Test;
Expand Down Expand Up @@ -92,4 +93,18 @@ public void preventsNoProperties() throws Exception {

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")));
}
}

0 comments on commit 1ee347c

Please sign in to comment.