SpringBoot操作MongoDB

1、SpringBoot操作MongoDB

这里我基于Spring官方文档写的demo,自行官网下载安装MongoDB,使用默认端口,在MongoDB创建数据库名为lk

image.png

创建springboot项目,引入MongoDB依赖:
2019年8月28日 20:04:11

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

2、application配置连接MongoDB:

spring.data.mongodb.uri=mongodb://localhost:27017/lk

或者:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=lk
# 默认没有账号密码
#spring.data.mongodb.username=
#spring.data.mongodb.password=

官方配置如下:

<beans>

  <mongo:mongo-client host="localhost" port="27017">
    <mongo:client-options connections-per-host="8"
                   threads-allowed-to-block-for-connection-multiplier="4"
                   connect-timeout="1000"
                   max-wait-time="1500}"
                   auto-connect-retry="true"
                   socket-keep-alive="true"
                   socket-timeout="1500"
                   slave-ok="true"
                   write-number="1"
                   write-timeout="0"
                   write-fsync="true"/>
  </mongo:mongo-client>

</beans>

3、在测试类中演示

实体类如下:

    class User {
        private int id;
        private String name;
        private String sex;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        /**
         * 用于打印对象内容
         */
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", sex='" + sex + '\'' +
                    '}';
        }
    }

3-1插入对象

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void contextLoads() {
        User user = new User();
        user.setId(1);
        user.setName("凌康");
        user.setSex("男");
       mongoTemplate.insert(user);
        user.setId(2);
        user.setName("李白");
        user.setSex("男");
        mongoTemplate.insert(user);
        log.info("插入成功!");
    }
image.png

3-2查找对象

    @Test
    public void find() throws Exception {
        User user=new User();
        List<User> users=mongoTemplate.findAll(User.class);
        users.forEach(u -> {
            log.info(u.toString());
        });
    }

控制台输入如下:


image.png

根据id查找对象

        User user=mongoTemplate.findById(1,User.class);
        log.info(user);

或者


3-3更新对象

    @Test
    public void update(){
        mongoTemplate.updateFirst(query(where("name").is("凌康")), Update.update("name","我是凌康"),User.class);
    }
update.png

3-4删除对象

    @Test
    public void delete(){
        User user=new User();
        user.setId(2);
        mongoTemplate.remove(user);
    }

总体代码:

package com.linke.mongodb;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongodbApplicationTests {
    private static final Log log = LogFactory.getLog(MongodbApplicationTests.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void contextLoads() {
        User user = new User();
        user.setId(1);
        user.setName("凌康");
        user.setSex("男");
       mongoTemplate.insert(user);
        user.setId(2);
        user.setName("李白");
        user.setSex("男");
        mongoTemplate.insert(user);
        log.info("插入成功!");
    }

    @Test
    public void find() throws Exception {
        User user=new User();
        List<User> users=mongoTemplate.findAll(User.class);
        users.forEach(u -> {
            log.info(u.toString());
        });
    }

    @Test
    public void update(){
        mongoTemplate.updateFirst(query(where("name").is("凌康")), Update.update("name","我是凌康"),User.class);
    }

    @Test
    public void delete(){
        User user=new User();
        user.setId(2);
        mongoTemplate.remove(user);
    }


    class User {
        private int id;
        private String name;
        private String sex;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        /**
         * 用于打印对象内容
         */
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", sex='" + sex + '\'' +
                    '}';
        }
    }

}

更多方法:

查看官方文档:
https://docs.spring.io/spring-data/mongodb/docs/2.1.10.RELEASE/reference/html/#mongodb-connectors

推荐阅读更多精彩内容