MongoTemplate


MongoTemplate 提供了对MongoDB操作的模板,能够满足crud,它的设计和Spring的JdbcTemplate很相似。除了Spring Data Mongo 外的另外一种操作MongoDB的方式。

查询操作

find(Query query, Class<T> entityClass) 
find(Query query, Class<T> entityClass, String collectionName) 
findById(Object id, Class<T> entityClass) 
findById(Object id, Class<T> entityClass, String collectionName)
findAll(Class<T> entityClass) 
findAll(Class<T> entityClass, String collectionName) 

最常用的以上这6个了,条件查询、根据id查询、查询全部;
我们可以看到重载方法,差了 一个String collectionName,如果没有这个参数,那么它会去找实体类@Document注解下的collection属性;如果没有找到,那么默认实体名作为集合名
findById和findAll用法简单,我们主要来看看这个条件查询find(Query query, Class entityClass)
参数Query是什么,怎么用

Query

Query:MongoDB查询对象,包括了条件,排序,分页等等
构造函数

Query() {}
Query(CriteriaDefinition criteriaDefinition)

方法

//添加查询标准或者说是查询条件到Query 
Query addCriteria(CriteriaDefinition criteriaDefinition)
//设置返回结果前要跳过的文档数
Query skip(long skip)
//将返回的文档数限制为{@code limit}
 Query limit(int limit) 
// 添加分页
Query with(Pageable pageable) 
// 添加排序
Query with(Sort sort) 
......

Query addCriteria(CriteriaDefinition criteriaDefinition):添加查询条件。
CriteriaDefinition是什么?它是一个查询标准定义,把它看做查询条件,看看它的实现类

在这里插入图片描述
TextCriteria:用于全文搜索
Criteria:创建查询的核心类,遵循 fluent API,即可以链式编程,定义了很多静态方法,这样可以方便把条件拼在一起。它最常用的
GridFsCriteria:专用于GridFs

Criteria

属性

  private static final Object NOT_SET = new Object();
	
	// key 代表查询条件的字段, 比如我想查 nickname = “小爱”
	// nickname将会赋值给这个key
	private @Nullable String key;
	// 可以拼接条件的原因,多个条件都会放到criteriaChain里
	private List<Criteria> criteriaChain;
	// map<运算符,“运算的值”> , 比如要查评论>10 ,则criteria.put("$gt", 10)
	private LinkedHashMap<String, Object> criteria = new LinkedHashMap<String, Object>();
	// 查询值参数, nickname = “小爱”,那么“小爱”赋值给isValue 
	private @Nullable Object isValue = NOT_SET;

构造

public Criteria() {
		this.criteriaChain = new ArrayList<Criteria>();
	}

	public Criteria(String key) {
		this.criteriaChain = new ArrayList<Criteria>();
		this.criteriaChain.add(this);
		this.key = key;
	}

	protected Criteria(List<Criteria> criteriaChain, String key) {
		this.criteriaChain = criteriaChain;
		this.criteriaChain.add(this);
		this.key = key;
	}

方法

// 该方法给key赋值,但还需要给isValue 赋值或者给criteria赋值,这样才能组成一个完整查询条件
//相当于指定作为查询条件的字段,如同mysql 中 的 where id=1,这个id就是key.
where(String key)
 // 相等于mysql中的 = 操作; o给isValue赋值,Criteria .where("_id").is(1)->_id = 1
Criteria is(@Nullable Object o)
//不等于
Criteria ne(@Nullable Object o)
//小于
Criteria lt(Object o)
//小于等于
Criteria lte(Object o)
;//大于>
Criteria gt(Object o)
;//大于等于>=
Criteria gte(Object o)
//in
Criteria in(Object... o)
//not in
Criteria nin(Object... o) 
// and 条件拼接并把key赋值
 Criteria and(String key)
 // 不为null
 Criteria not()
 // 
 not(@Nullable Object value) 
 
//用正则来模糊查询
Criteria regex(String re)
........

插入操作

MongoTemplate提供的插入方法

void insert(Object objectToSave)
insert(Object objectToSave, String collectionName)

删除操作

MongoTemplate提供的删除操作

DeleteResult remove(Query query, String collectionName)
DeleteResult remove(Query query, Class<?> entityClass)
DeleteResult remove(Query query, Class<?> entityClass, String collectionName)

可以看到都是根据条件进行删除,Query的用法上文已提到

更新操作

 UpdateResult upsert(Query query, Update update, Class<?> entityClass)
 UpdateResult upsert(Query query, Update update, String collectionName)
 UpdateResult upsert(Query query, Update update, Class<?> entityClass, String collectionName)

 UpdateResult updateFirst(Query query, Update update, Class<?> entityClass)
 UpdateResult updateFirst(final Query query, final Update update, final String collectionName)
 UpdateResult updateFirst(Query query, Update update, Class<?> entityClass, String collectionName)
 
 UpdateResult updateMulti(Query query, Update update, Class<?> entityClass)
 UpdateResult updateMulti(final Query query, final Update update, String collectionName)
 UpdateResult updateMulti(final Query query, final Update update, Class<?> entityClass, String collectionName)

upsert :修改满足条件的所有document
updateFirst:修改满足条件的第一个document
updateMulti:与upsert区别就是,update:查不到就不更新,updateMulti:查不到就插入一条满足查询条件的。

项目实战

1. pom 依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

2. 配置文件

spring:
  data:
    mongodb:
      host: 127.0.0.1
      database: spitdb

3. service

@Service
public class SpitService {

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询所有
     * @return
     */
    public List<Spit> findAll() {
//        spitDao.findAll();
        return mongoTemplate.findAll(Spit.class);
    }

    /**
     * 根据id查询
     * @param spitId
     * @return
     */
    public Spit findById(String spitId) {
//        spitDao.findById(spitId).get();
        return mongoTemplate.findById(spitId,Spit.class,"spit");
    }

    /**
     * 新增
     * @param spit
     */
    public void save(Spit spit) {
        spit.set_id(String.valueOf(idWorker.nextId()));
        spit.setPublishtime(new Date());        // 发布日期
        spit.setVisits(0);      // 浏览量
        spit.setShare(0);       // 分享数
        spit.setThumbup(0);     // 点赞数
        spit.setComment(0);     // 回复数
        spit.setState("1");     // 状态
//        spitDao.save(spit);
//        如果有父节点,那么父节点评论加1
        if (StringUtils.isNotEmpty(spit.getParentid())){
            Query query = new Query(Criteria.where("_id").is(spit.getParentid()));
            Update update = new Update();
            update.inc("comment",1);
            mongoTemplate.updateFirst(query,update,"spit");
        }
        mongoTemplate.save(spit,"spit");
    }

    public void update(Spit spit) {
        spitDao.save(spit);
    }

    public void deleteById(String spitId) {
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(spitId)),"spit");
//        spitDao.deleteById(spitId);
    }

    public Page<Spit>  findByParentId(String parentid, int page, int size) {
        Page<Spit> spitPage = spitDao.findByParentid(parentid, PageRequest.of(page - 1, size));
        return spitPage;
    }

    /**
     * 点赞
     * 用户不能重复点赞
     * @param spitId
     */
    public Result thumbup(String spitId) {
        String userid="newheart_666";
        Object o = redisTemplate.opsForValue().get(userid + "_" + spitId);
        if (o!=null){
            return new Result(StatusCode.ERROR, false, "用户已点赞");
        }
//        点赞自增
        redisTemplate.opsForValue().set(userid + "_" + spitId,"点赞");
        Query query = new Query();
        query.withHint("点赞自增");
        query.addCriteria(Criteria.where("_id").is(spitId).and("nickname").is("小爱").and("thump"));
        Update update = new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query,update,"spit");
        return new Result(StatusCode.OK, true, "点赞成功");
    }
}

上面这个serive 将Spring Data Mongo和 MongoTemplate一起用了,希望大家能将就看看。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章