为了账号安全,请及时绑定邮箱和手机立即绑定

当Spring遇见MongoDB,五分钟搞定CRUD

标签:
Java MongoDB

一、引入相关依赖

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.9.5.RELEASE</version>
        </dependency>

    </dependencies>

二、配置MongoDB连接
spring官网提供了很多种配置方式 spring-mongo-reference
这是其中一种

package me.sclove.admin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.Mongo;

@Configuration
public class MongoConfig {

    @Bean
    public MongoClientFactoryBean mongo(){
        MongoClientFactoryBean factoryBean = new MongoClientFactoryBean();
        factoryBean.setHost("localhost"); // 数据库地址
        factoryBean.setPort(27017); // 端口
        return factoryBean;
    }

    @Bean
    public MongoOperations mongoTemplate(Mongo mongo){
        // 操作Mongo的模板类,提供了非常纯粹的oo操作数据库的api
        return new MongoTemplate(mongo, "dbtest"); // dbtest 为数据库名
    }

}

三、编写测试类
①测试实体类


public class Person {

    private String id;
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

②Test类

  • insert
    @Test
    public void insert() {
        AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext(
                MongoConfig.class);
        MongoOperations mongoOps = a.getBean(MongoOperations.class);
        Person person = new Person("white", 23);
        // 单条插入
        mongoOps.insert(person);
        List<Person> persons = new ArrayList<Person>();
        for (int i = 1; i <= 20; i++) {
            persons.add(new Person("white" + i + "号", 20 + i));
        }
        // 批量插入
        mongoOps.insertAll(persons);
        a.close();
    }

一行代码搞定了Mongo的插入操作,这里我们并没有设置Mongo的集合名,只是传入了一个实体对象,初步猜想MongoOperations 模板类应该是把实体类的类名或者全类名作为了集合的名称,用一个Mongo GUI工具打开数据库
这里写图片描述

可以看到,基本印证了猜想,这里MongoOperations 把类名小写之后作为了Mongo集合的名称,而把当前类的全类名作为了一个字段存储到了数据库中

  • query
    为了方便操作
    // 静态导入
    import static org.springframework.data.mongodb.core.query.Criteria.where;
    import static org.springframework.data.mongodb.core.query.Update.update;

    @Test
    public void query() {
        AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext(
                MongoConfig.class);
        MongoOperations mongoOps = a.getBean(MongoOperations.class);
        // 查询匹配条件的第一条数据
        Person findOne = mongoOps.findOne(new Query(where("name").is("white")), Person.class);
        System.out.println(findOne);
        // 查询所有记录
        List<Person> all = mongoOps.findAll(Person.class);
        System.out.println(all);
        // 查询age >= 25 and age < 30
        Query query = new Query(where("age").gte(25).lt(30));
        List<Person> findByCondition = mongoOps.find(query , Person.class);
        System.out.println(findByCondition);

        // 原生命令方式
        BasicQuery bq =new BasicQuery("{name:'white'}");

        Person findOne2 = mongoOps.findOne(bq, Person.class);
        System.out.println(findOne2);

        a.close();
    }
  • delete

    @Test
    public void delete() {
        AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext(
                MongoConfig.class);
        MongoOperations mongoOps = a.getBean(MongoOperations.class);
        // 删除age>=25的所有记录
        WriteResult remove = mongoOps.remove(new Query(where("age").gte(25)),Person.class);

        // 查出第一条匹配的记录并把这条记录删除 阅后即焚 
        Person findAndRemove = mongoOps.findAndRemove(new Query(where("name").is("white")), Person.class);
        System.out.println(findAndRemove);
        // 按对象删除
        Person p = mongoOps.findOne(new Query(where("age").is(22)), Person.class);
        mongoOps.remove(p);
        // 删除集合
        mongoOps.dropCollection(Person.class);
        a.close();
    }
  • update
    @Test
    public void updateTest() {
        AnnotationConfigApplicationContext a = new AnnotationConfigApplicationContext(
                MongoConfig.class);
        MongoOperations mongoOps = a.getBean(MongoOperations.class);
        // 更新一条
        mongoOps.updateFirst(new Query(where("age").is(23)), update("name","white小哥"), Person.class);
        // 更新多条
        mongoOps.updateMulti(new Query(where("age").lte(23)), update("name","white大哥"), Person.class);
        a.close();
    }
点击查看更多内容
17人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消