spring boot mongodb分页查询

本例基于spring-data-mongodb 1.10.4 版本

@Repository
public interface AttachmentDao extends MongoRepository {
    List findByTypeAndName(String type, String name);
}
public Page findAttachmentPage(QueryAttachmentReq req) {
    Sort.Order order = new Sort.Order(Sort.Direction.DESC, "uploadTime");
    Sort sort = new Sort(order);
    PageRequest pageRequest = new PageRequest(req.getPageNum() - 1, req.getPageSize(), sort);
    ExampleMatcher matcher = ExampleMatcher.matching()
            .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询
            .withIgnoreCase(true) //改变默认大小写忽略方式:忽略大小写
            .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains()) //采用“包含匹配”的方式查询
            .withIgnorePaths("pageNum", "pageSize");  //忽略属性,不参与查询;
    Example example = Example.of(req, matcher);
    return attachmentDao.findAll(example, pageRequest);
}

总结下遇到的问题
1 PageRequest 分页page从0开始,所以传入页码需要减去1
2 默认保存数据会插入_class字段,若想去掉需要做额外操作

@Configuration
@Slf4j
public class MongoConfig {
    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        } catch (NoSuchBeanDefinitionException e) {
            log.warn("MappingMongoConverter setCustomConversions失败", e.getBeanName());
        }
        // Don't save _class to mongo
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return mappingConverter;
    }
}
 

 

你可能感兴趣的:(JAVA,spring,boot)