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一起用了,希望大家能將就看看。

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