Jose
Jose

Reputation: 1819

Custom Query with Pageable. Spring Data MongoDB ( 1.10.9 )

I have created a custom repository:

// my repository:

@SuppressWarnings("unused")
@Repository
public interface PrlRepository extends MongoRepository<Prl, String>, PrlRepositoryCustom {

// my interface:

public interface PrlRepositoryCustom {

List<Prl> find(FilterPrlDTO filterPrlDTO);

}

// my implementation

@Override
public List<Prl> find(FilterPrlDTO filterPrlDTO) {
    List<Criteria> andCriteria = new ArrayList<>();

    if (filterPrlDTO.getInicioCaduca() != null) {
        andCriteria.add(Criteria.where("caducidad").gte(filterPrlDTO.getInicioCaduca()));
    }
    if (filterPrlDTO.getFinCaduca() != null) {
        andCriteria.add(Criteria.where("caducidad").lte(filterPrlDTO.getFinCaduca()));
    }
    if (filterPrlDTO.getActivo() != null) {
        andCriteria.add(Criteria.where("activo").is(filterPrlDTO.getActivo()));
    }

    Criteria orCriteria = new Criteria().andOperator(andCriteria.toArray(new Criteria[andCriteria.size()]));
    return mongoOperations.find(new Query().addCriteria(orCriteria), Prl.class);
}

It works correctly, but I need it to be Pageable.

Can someone help me how to implement it? I've been looking at forums and documentation but I do not see anything that I can serve

Thank you very much.

Upvotes: 4

Views: 6314

Answers (2)

Sunand Padmanabhan
Sunand Padmanabhan

Reputation: 656

MongoRepository actually implements PagingAndSortingRepository which allows you to implement pagination.

You can pass the Pageable request along with the Query class, here is a sample of how to do it:

Pageable pageable = new PageRequest(pageNumber, dataSize);
Query query = new Query(); 

public Page<T> findAll(Query query, Pageable pageable) {
    Long count = count(); //Issue a count query here for the collection
    List<T> list = findAll(query.with(pageable));
    return new PageImpl<T>(list, pageable, count);
}

For more information and samples look here:
SimpleMongoRepository example

Upvotes: 3

Jose
Jose

Reputation: 1819

Structure to search with large filters, which will enter the Criteria based on the search parameters and the result is paged:

public Page<AccionOportunidad> filter(Pageable pageable) {

    Query query = new Query();

    // criterias 
    query.addCriteria(Criteria.where("id").in("xxx"));

    query.with(pageable);
    List<AccionOportunidad> list = mongoOperations.find(query, AccionOportunidad.class);

    return PageableExecutionUtils.getPage(list, pageable,
            () -> mongoOperations.count(query, AccionOportunidad.class));

}

Upvotes: 2

Related Questions