使用Spring Data操作MongoDB--MongoOperations

MongoDB属于NoSQL数据的一种,是一个“存储数据”的系统,增删改查可以添加很多条件,就像SQL数据库一样灵活。

官方文档提供的原生java语句写法虽然种类齐全,但是使用起来极其不便,为此Spring对MongoDB的操作进行了类似于JDBCTemplate的封装。在集成Spring后可以直接使用 MongoOperations 来达到我们的目的。

对于MongoDB如何集成Spring网上有很多教程,我们在这里不再赘述。可以参考下面的链接:

https://www.cnblogs.com/jmcui/archive/2018/03/31/8672492.html

https://www.cnblogs.com/zishengY/p/8467176.html

https://blog.csdn.net/qq_16313365/article/details/70142729

一、插入一条数据

mongoOperations.insert();

使用mongoOperations来向数据库插入数据时,是不需要指定集合名称的,会根据类名来自动创建一个集合,用于存放数据,并且在保存进mongodb后,会自动为数据增加上类的包路径。保存形式如下:

{
        "_id" : ObjectId("5c0651664c6706efff0fcd94"),
        "_class" : "com.ys.mongodb.entity.Cat",     // 应该是spring在向mogodb中插入时自动添加的
        "name" : "大咪",
        "sex" : "female",
        "age" : 5,
        "hobbyList" : [
                "玩毛线球",
                "看电视",
                "凝望",
                "吃小鱼干"
        ],
        "createTime" : ISODate("2018-12-04T10:05:26.471Z"),
        "master" : "刘小皮"
}

二、同样的mongoOperations也支持批量插入的操作

mongoOperations.insertAll();

三、指定查询文档

Criteria criteria = Criteria.where("name").is(name);
Query query = new Query(criteria);
mongoOperations.find(query, Cat.class);

mongoOperations将所有你想要指定的条件都封装为一个Query对象,这样你在进行条件查询,删除,更新等操作时,可以很方便的复用Query对象,而不需要为每一个条件一样,但操作不一样的语句写一遍条件。在实际使用中,Criteria用于指定文档中的具体信息,Query则用于指定一些排序,分页的逻辑。

1、组合条件查询

很多时候,我们需要查询的条件不止一个,而是有很多的联合起来的。这个时候,可以使用Criteria.and和Criteria.or来将条件进行连接。例如下面根据name与age进行查询:

        Criteria criteria = Criteria.where("name").is(name);
        criteria.and("age").is(1);

根据name或者age查询则改为这样:

        Criteria criteria = Criteria.where("name").is(name);
        criteria.or("age").is(1);

2、如果文档中包含数组,又想根据数据中的数据来作为条件,可以这样写

        Criteria criteria = Criteria.where("hobbyList").in(hobbyList);

构建一个对应的list就可以根据我们所构建的list来精确匹配数组中的元素,注意上面的写法是精确匹配,模糊匹配的语句类似,大家自己探索。

3、分页与排序

mongoOperations的操作实际上封装与jdbcTemplate类似,因此在分页与排序上语法类似。

分页:

Pageable pageable = new PageRequest(offset,limit);
query.with(pageable);

排序:

        Query query = new Query().with(new Sort(Sort.Direction.DESC,"createTime"));

四、范围条件

        Criteria criteria = Criteria.where("age").gte(min).lte(max);
        Query query = new Query(criteria);

上面的例子演示了范围为 min<=age<=max的条件,注意这里不能分为

Criteria.where("age").gte(min);
Criteria.where("age").lte(max);

这样的两条语句来写,会报重复条件名称错误。

下面的代码演示了对实体类Cat的基本mongoDB操作

com.ys.mongodb.entity.Cat

package com.ys.mongodb.entity;

import lombok.*;

import java.util.Date;
import java.util.List;

/**
 * @author yangshuo
 * @date 2018/12/4 16:11
 */
@Builder
@Setter
@Getter
@ToString
public class Cat {
    private String name;
    private String sex;
    private Integer age;
    private List<String> hobbyList;
    private Date createTime;
    private String master;
}

com.ys.mongodb.dao.CatOperations

package com.ys.mongodb.dao;

import com.ys.mongodb.entity.Cat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yangshuo
 * @date 2018/12/4 16:18
 */
@Service
public class CatOperations {

    @Autowired
    private MongoOperations mongoOperations;

    /**
     * 向mongodb中插入一条数据
     */
    public void insert(Cat cat){
        mongoOperations.insert(cat);
    }

    /**
     * 批量插入
     */
    public void batchInsert(List<Cat> catList){
        mongoOperations.insertAll(catList);
    }

    /**
     * 根据名字查询
     */
    public List<Cat> queryByName(String name){
        Criteria criteria = Criteria.where("name").is(name);
        Query query = new Query(criteria);
        return mongoOperations.find(query, Cat.class);
    }

    /**
     * 组合条件查询
     */
    public List<Cat> queryByNameAndAge(String name, int age){
        Criteria criteria = Criteria.where("name").is(name);
        criteria.and("age").is(1);
        Query query = new Query(criteria);
        return mongoOperations.find(query, Cat.class);
    }

    /**
     * 根据list里的数据查询
     */
    public List<Cat> queryByHobbyList(List<String> hobbyList){
        Criteria criteria = Criteria.where("hobbyList").in(hobbyList);
        Query query = new Query(criteria);
        return mongoOperations.find(query, Cat.class);
    }

    /**
     * 根据时间排序
     */
    public List<Cat> orderByCreateTime(){
        Query query = new Query().with(new Sort(Sort.Direction.DESC,"createTime"));
        return mongoOperations.find(query, Cat.class);
    }

    /**
     * 根据年龄区间查询
     */
    public List<Cat> queryByAgeRange(int min, int max){
        Criteria criteria = Criteria.where("age").gte(min).lte(max);
        Query query = new Query(criteria);
        return mongoOperations.find(query, Cat.class);
    }

    /**
     * 其余的条件删除与更新都是先拼好Query与查询类型
     * 只是换了最后调用的函数,这里不再演示
     */
    public void deleteAll(){
        mongoOperations.dropCollection(Cat.class);
    }
}

com.ys.mongodb.dao.CatOperationsTest

package com.ys.mongodb.dao;

import com.ys.mongodb.entity.Cat;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.*;

/**
 * @author yangshuo
 * @date 2018/12/4 17:49
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@Slf4j
public class CatOperationsTest {

    @Autowired
    private CatOperations catOperations;

    @Test
    public void insert() throws Exception {
        List<String> hobbyList = new ArrayList<String>();
        hobbyList.add("玩毛线球");
        hobbyList.add("凝望");
        hobbyList.add("吃小鱼干");
        Cat cat = Cat.builder().name("小咪")
                .sex("female")
                .age(1)
                .hobbyList(hobbyList)
                .createTime(new Date())
                .master("刘忽悠")
                .build();
        catOperations.insert(cat);
    }

    @Test
    public void batchInsert() throws Exception {
        List<Cat> cats = new ArrayList<>();
        List<String> hobbyList = new ArrayList<>();
        hobbyList.add("玩毛线球");
        hobbyList.add("看电视");
        hobbyList.add("凝望");
        hobbyList.add("吃小鱼干");
        Cat cat = Cat.builder().name("大咪")
                .sex("female")
                .age(5)
                .hobbyList(hobbyList)
                .createTime(new Date())
                .master("刘小皮")
                .build();
        cats.add(cat);
        Cat cat1 = Cat.builder().name("阿飞")
                .sex("female")
                .age(3)
                .hobbyList(hobbyList)
                .createTime(new Date())
                .master("刘傻瓜")
                .build();
        cats.add(cat1);
        catOperations.batchInsert(cats);
    }

    @Test
    public void queryByName() throws Exception {
        List<Cat> cats = catOperations.queryByName("小咪");
        log.info("按名字查询:{}",cats);
    }

    @Test
    public void queryByNameAndAge() throws Exception {
        List<Cat> cats = catOperations.queryByNameAndAge("阿飞", 3);
        log.info("按名字与年龄查询:{}",cats);
    }

    @Test
    public void queryByHobbyList() throws Exception {
        List<String> hobbyList = new ArrayList<String>();
        hobbyList.add("玩毛线球");
        hobbyList.add("凝望");
        hobbyList.add("吃小鱼干");
        List<Cat> cats = catOperations.queryByHobbyList(hobbyList);
        log.info("精确查询数组中的数据:{}",cats);
    }

    @Test
    public void orderByCreateTime() throws Exception {
        List<Cat> cats = catOperations.orderByCreateTime();
        log.info("按照时间排序:{}",cats);
    }

    @Test
    public void queryByAgeRange() throws Exception {
        List<Cat> cats = catOperations.queryByAgeRange(2, 5);
        log.info("按照年龄范围查询:{}",cats);
    }

    @Test
    public void deleteAll() throws Exception {
        catOperations.deleteAll();
    }

}

猜你喜欢

转载自blog.csdn.net/yshuoo/article/details/84789788