因文档比较大,有时候findAll 不想返回所有数据.没有找到默认的findAll 能够include 或者 exclude 的方法,所以想办法扩展一下实现类

query.fields().include()
query.fields().exclude()

调试结果 SimpleMongoRepository 为 MongoRepository 的默认实现类,那么继承 SimpleMongoRepository 做一点修改

/**
* Created by laizhenwei on 2017/10/25
*/
public class MySimpleMongoRepository <T, ID extends Serializable> extends SimpleMongoRepository<T, ID> {
private final MongoOperations mongoOperations;
private final MongoEntityInformation<T, ID> entityInformation; public MySimpleMongoRepository(MongoEntityInformation<T, ID> metadata, MongoOperations mongoOperations) {
super(metadata, mongoOperations);
this.entityInformation = metadata;
this.mongoOperations = mongoOperations;
} public <S extends T> Page<S> findAll(final Example<S> example,final Query query, Pageable pageable) {
Assert.notNull(example, "Sample must not be null!");
query.addCriteria((new Criteria()).alike(example)).with(pageable);
List<S> list = this.mongoOperations.find(query, example.getProbeType(), this.entityInformation.getCollectionName());
return PageableExecutionUtils.getPage(list, pageable, () -> mongoOperations.count(query, example.getProbeType(),entityInformation.getCollectionName()));
}
}

OrderInfoRepository

/**
* Created by laizhenwei on 2017/10/25
*/
public interface OrderInfoRepository extends MongoRepository<OrderInfo,ObjectId> { Page<OrderInfo> findAll(final Example<OrderInfo> example, final Query query, Pageable pageable); }

MongoConfig

/**
* Created by laizhenwei on 2017/10/25
*/
@Configuration
@EnableMongoRepositories(basePackages = "com.example.mongo.Repository",repositoryBaseClass = MySimpleMongoRepository.class)
public class MongoConfig {
}

JunitTest

 @Test
public void findPage(){
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("buyer", ExampleMatcher.GenericPropertyMatchers.exact())
.withMatcher("phone",ExampleMatcher.GenericPropertyMatchers.exact()) OrderInfo orderInfo = new OrderInfo();
orderInfo.setBuyer("A君");
orderInfo.setPhone("13422981024"); Example<OrderInfo> example = Example.of(orderInfo,matcher); Query query = new Query();
query.fields().include("orderInfo");
Page<OrderInfo> page = orderInfoRepository.findAll(example,query,new PageRequest(0,10));
List<OrderInfo> orderInfos = page.getContent(); Assert.assertTrue(orderInfos.stream().filter(val->val.getPhone().equals("13422981024")).count()==1); System.out.println(orderInfos.size());
System.out.println(orderInfos.get(0).getOrderDetails());
}

Spring data mongodb 替换 Repository 实现类,findAll 排除 字段-LMLPHP

04-26 01:49