A simple use case is to use a custom repository with the Query and SimpleMongoRepository classes.
CustomerRepository.java
@Repository
public interface CustomerRepository extends ResourceRepository<Customer, String> {
}
ResourceRepository.java
@NoRepositoryBean
public interface ResourceRepository<T, I> extends MongoRepository<T, I> {
Page<T> findAll(Query query, Pageable pageable);
}
ResourceRepositoryImpl.java
@SuppressWarnings("rawtypes")
public class ResourceRepositoryImpl<T, I> extends SimpleMongoRepository<T, I> implements ResourceRepository<T, I> {
private MongoOperations mongoOperations;
private MongoEntityInformation entityInformation;
public ResourceRepositoryImpl(final MongoEntityInformation entityInformation, final MongoOperations mongoOperations) {
super(entityInformation, mongoOperations);
this.entityInformation = entityInformation;
this.mongoOperations = mongoOperations;
}
@Override
public Page<T> findAll(final Query query, final Pageable pageable) {
Assert.notNull(query, "Query must not be null!");
long total = mongoOperations.count(query, entityInformation.getJavaType(), entityInformation.getCollectionName());
List<T> content = mongoOperations.find(query.with(pageable), entityInformation.getJavaType(), entityInformation.getCollectionName());
return new PageImpl<T>(content,pageable,total);
}
}
CustomerService.java
@RequiredArgsConstructor
@Service
public class CustomerService {
private final CustomerRepository repository;
/**
* @param customerId
* @param limit the size of the page to be returned, must be greater than 0.
* @param page zero-based page index, must not be negative.
* @return Page of {@link Customer}
*/
public Page<Customer> getCustomers(String customerId, int limit, int page) {
Query query = new Query();
query.addCriteria(Criteria.where("customerId").is(customerId));
return repository.findAll(query, PageRequest.of(page, limit, Sort.by(Sort.Direction.ASC, "customerId")));
}
public List<Customer> getCustomersList(String customerId, int limit, int page) {
Page<Customer> customerPage = getCustomers(customerId, limit, page);
return customerPage.getContent();
}
}
A reference with specific criteria:
https://dzone.com/articles/advanced-search-amp-filtering-api-using-spring-dat