Spring Data with MongoDB
节选自《Netkiller Spring Cloud 手札》
MongoRepository
扫描仓库接口
默认不需要设置,除非你的包不在当前包下,或者命令不是 repository。
@EnableMongoRepositories(basePackages = "cn.netkiller.repository")
findAll()
@RequestMapping(value = "read", method = RequestMethod.GET, produces = { "application/xml", "application/json" })
@ResponseStatus(HttpStatus.OK)
public List<Withdraw> read() {
return repository.findAll();
}
deleteAll()
repository.deleteAll();
save()
repository.save(new City("Shenzhen", "China"));
count()
@RequestMapping("count")
public long count() {
return repository.count();
}
exists() 判断是否存在
boolean isExists = userRepository.exists(user.getId());
existsById()
memberRepository.existsById(id);
findByXXXX
List<User> findByName(String name);
List<User> users = userRepository.findByName("Eric");
findAll with OrderBy
order by boolean 布尔型数据排序
因为 boolean 数据 true = 1, false = 0 所以 ASC false 会排列在前面。所有很多时候而我们需要 DESC 排序
List<ShippingAddress> shippingAddress = shippingAddressRepository.findAllByMemberIdOrderByDefaultsDesc(memberId);
findAll with Sort
List<User> users = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
FindAll with Pageable
Pageable pageable = PageRequest.of(0, 1);
Page<User> page = userRepository.findAll(pageable);
List<User> users = pages.getContent();
PageRequest - springboot 1.x 旧版本
Page<User> findByLastname(String lastname, Pageable pageable);
@RequestMapping(value = "read/{size}/{page}", method = RequestMethod.GET, produces = { "application/xml", "application/json" })
@ResponseStatus(HttpStatus.OK)
public List<Withdraw> readPage(@PathVariable int size, @PathVariable int page){
PageRequest pageRequest = new PageRequest(page-1,size);
return repository.findAll(pageRequest).getContent();
}
URL翻页参数,每次返回10条记录
第一页 http://localhost:8080/v1/withdraw/read/10/1.json
第二页 http://localhost:8080/v1/withdraw/read/10/2.json
...
第五页 http://localhost:8080/v1/withdraw/read/10/5.json
StartingWith 和 EndingWith
List<User> findByNameStartingWith(String regexp);
List<User> findByNameEndingWith(String regexp);
List<User> users = userRepository.findByNameStartingWith("N");
List<User> users = userRepository.findByNameEndingWith("o");
Between
数值范围
List<User> findByAgeBetween(int ageGT, int ageLT);
List<User> users = userRepository.findByAgeBetween(20, 50);
日期范围,取值 e.g. 2018-07-04 00:00:00 and 2018-07-04 23:59:59
List<Member> findByCreatedDateBetween(DateTime start, DateTime end);
List<Member> findByCreatedDate(@Temporal(TemporalType.DATE) Date date);
Before / After
List<Assets> findAllByUpdateDateBefore(Date yesterday);
List<Assets> findAllByUpdateDateBeforeAndStatus(Date yesterday, String status);
List<Assets> findAllByUpdateDateAfter(Date yesterday);
@Query
public interface PersonRepository extends MongoRepository<Person, String> {
@Query("{ 'name' : ?0 }")
List<Person> findWithQuery(String userId);
}
@Query(value = "{'statusHistories':{$elemMatch:{'status':{$in:['PROCESSABLE']}}},'created' : { '$gt' : { '$date' : ':?0' } , '$lt' : { '$date' : ':?1'}}}", count = true)
Long countMe(@Param("dateFrom") Date datefrom, @Param("dateTo") Date dateTo);