Thursday, October 4, 2012

Sorting Mongo collection with Spring Data

One of my friend (a smart guy and a good developer) came up to me with a question "I'm trying to sort the results and I follow the documentation but still no luck" then he provded the code to find a problem:
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Sort;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;

public interface EventRepository extends PagingAndSortingRepository<ApplicationEvent, ObjectId>{
    @Query("{'created' : {$lt: ?0}, 'status': ?1, 'active':true}")
    List<ApplicationEvent> findAllByStatus(long date, String status, Sort sort);
}
At first look everything is ok, the class is designed in according to docs and tutorials. It just didn't work. What's wrong with this code? After awhile we'd figured it out. The answer is when you try to sort results with Spring Data and Repositories and the underlying database is Mongo, please check twice if you aren't using
import org.springframework.data.mongodb.core.query.Sort;
insted of
import org.springframework.data.domain.Sort;
It's so embarrassing, but after replacing with to the right one everythig just started working..

No comments:

Post a Comment