在用Mongo库的时候,无法用generator生成底层,所以需要自己写实现。
查询的话就用mongoTemplate代替mapper,
插入的时候:
mongoTemplate.insert(apiLog);
查询的时候:
Query query =newQuery();
if(StringUtils.isNotBlank(apiLog.getMerchantCode())) {
query.addCriteria(Criteria.where("merchantCode").regex(apiLog.getMerchantCode().trim(),"i"));
}
其实和之前的查询还是很相似的
主要是几个关键词,regex,is..
设置排序信息:
if(StringUtils.isBlank(pageable.getOrderProperty())) {
query.with(newSort(newSort.Order(Sort.DEFAULT_DIRECTION.DESC,"createTime")));
pageable.setOrderProperty("createTime");
pageable.setOrderDirection(Order.Direction.desc);
}else{
if(String.valueOf(pageable.getOrderDirection()).toUpperCase().equals("ASC")) {
query.with(newSort(newSort.Order(Sort.DEFAULT_DIRECTION.ASC,"createTime")));
}else{
query.with(newSort(newSort.Order(Sort.DEFAULT_DIRECTION.DESC,"createTime")));
}
}
query.skip((pageable.getPageNumber() -1) *pageable.getPageSize()).limit(pageable.getPageSize());
list =mongoTemplate.find(query,ApiLog.class);
增删改查
新增
- 增:mongoTemplate.insert(apiLog);
- 批量新增:mongoTemplate.insertAll(apiLog);
删除
- 删:mongoTemplate.remove(apiLog);
按条件删除
Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());
Query query =newQuery(criteria);
mongoTemplate.remove(query, User.class);
删除全部
mongoTemplate.dropCollection(User.class);
修改 :
按主键修改
Criteria criteria = Criteria.where("id").is(user.getId());
Query query =newQuery(criteria);
Update update = Update.update("age", user.getAge()).set("name", user.getName());
mongoTemplate.updateFirst(query, update, User.class);
修改多条
Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());;
Query query =newQuery(criteria);
Update update = Update.update("name", user.getName()).set("age", user.getAge());
mongoTemplate.updateMulti(query, update, User.class);
查询 :
按主键查询:mongoTemplate.findById(id, User.class);
查询全部 :mongoTemplate.findAll(User.class);
-
按查询条件分页 :
Query query = getQuery(criteriaUser); query.skip(skip); query.limit(limit); returnmongoTemplate.find(query, User.class);
根据条件查询出来后 再去修改
Query query = getQuery(criteriaUser);
Update update = Update.update("age", updateUser.getAge()).set("name", updateUser.getName());
returnmongoTemplate.findAndModify(query, update, User.class);
计数:
Query query = getQuery(criteriaUser);
returnmongoTemplate.count(query, User.class);
多条件查询:
Query query =newQuery();
if(criteriaUser.getId() !=null) {
Criteria criteria = Criteria.where("id").is(criteriaUser.getId());
query.addCriteria(criteria);
}
if(criteriaUser.getAge() >0) {
Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());
query.addCriteria(criteria);
}
if(criteriaUser.getName() !=null) {
Criteria criteria = Criteria.where("name").regex("^"+ criteriaUser.getName());
query.addCriteria(criteria);
}
returnquery;
数据库语句
db.getCollection('selectTypeName').find({name:"New Zealand "})
db.getCollection('selectTypeName').remove({name:"新增1"})
db.getCollection('selectTypeName').update({name: 'New Zealand '}, {$set: {name: 'New Zealand'}}, false, true);