Search code examples
spring-data-mongodb

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.


Solution

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