该文仅仅为个人MongoDB测试案例,注释中的内容只是个人理解,如果有误请务必指出

目录

1、项目结构

2、MAVEN配置

3、Springboot配置文件

4、实体类

5、Service层

6、Controller层

7、Springboot 主程序代码

8、参考文章


1、项目结构

mongodb 分库 springboot mongodb java springboot_mongodb

 

2、MAVEN配置


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.LW1</groupId>
    <artifactId>com.LW1.TestMongoDB</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>com.LW1.TestMongoDB</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <!--mongodb 的包,必要-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3、Springboot配置文件


#服务配置
#开放端口号
server.port=8081
#更改访问链接前缀
server.servlet.context-path=/MongoTest

#mybatis 配置(可以省略,没必要配置 mybatis)
spring.datasource.url=jdbc:mysql://localhost:3306/homework1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#mongodb 连接
#mongodbTest 为数据库名(数据库需要自己建立并指定)
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/mongodbTest

#如果出现 json 字符串转换报错那就加这一句
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS= false




4、实体类


TestMsg

package com.LW1.dao;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.Serializable;

//@Document(collection = "Mongodb中的集合名")
@Document(collection = "myTest")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestMsg implements Serializable { //对应 Mongodb 的集合的实体类需要继承 Serializable 类

    String id;
    String username;
    String stuNum;
    Integer age;
    String moreTest;

}




TestMsg2

package com.LW1.dao;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.mongodb.core.mapping.Document;

//@Document(collection = "Mongodb中的集合名")
@Document(collection = "myTest")
@AllArgsConstructor
@NoArgsConstructor
@Data
public class TestMsg2 {

    String id;
    String username;
    String stuNum;
    Integer age;
    String moreTest;

}




5、Service层


package com.LW1.service;

import com.LW1.dao.TestMsg;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class TestMongoDBService {

    //获得 MongoTemplate 类
    //用 @Resource 吧,用 @Autowired 有时候会失灵
    @Resource
    MongoTemplate mongoTemplate;


    //创建集合(相当于 mysql 建表)
    public void createTable(){
        //创建集合 mongoTemplate.createCollection(集合名)
        /*MongoCollection<Document> myTest2 = */
        mongoTemplate.createCollection("myTest2");
        System.out.println("执行创建集合");
    }

    //删除集合(相当于 mysql 删表)
    public void deleteTable(){
        //删除集合 mongoTemplate.dropCollection(集合名);
        mongoTemplate.dropCollection("myTest2");
        //再次试着获取这个集合
        /*MongoCollection<Document> myTest2 = mongoTemplate.getCollection("myTest2");
        System.out.println(myTest2);*/
        System.out.println("执行删除集合");
    }


    //查询所有数据
    public List<TestMsg> selectAllInfo(){

        //查询条件可以写 1 不包括 1 来实现全部查询
        //Criteria criteria = Criteria.where("1").nin("1");

        //mongoTemplate.findAll(对应的实体类.class,要查询的集合名);
        List<TestMsg> testMsg = mongoTemplate.findAll(TestMsg.class,"myTest");
        return testMsg;
    }


    //按照条件查询指定数据
    public List<TestMsg> selectInfo(){

        //使用 Criteria 需要导入 MongoTemplate 类
        Criteria criteria = Criteria //配置查询条件
            .where("username").is("LW1")
            .and("age").is(22);

        //查询条件可以写 1 不包括 1 来实现全部查询
        //Criteria criteria = Criteria.where("1").nin("1");

        //new Query(配置好的查询对象)
        Query query = new Query(criteria);//生成查询语句

        //mongoTemplate.find(生成的查询语句对象, 对应要查询的集合的实体类.class,要查询的集合名);
        List<TestMsg> testMsg = mongoTemplate.find(query, TestMsg.class,"myTest");//执行查询语句

        return testMsg;
    }


    //插入多条数据
    public Collection insertInfo(){

        ArrayList arrayList = new ArrayList();
        arrayList.add(new TestMsg(null,"呱呱222","0000",9,"呱呱"));//直接插入实例化的对象,是 json 字符串就行
        arrayList.add(new TestMsg(null,"喔哦222","1111",12,"哇哦"));
        arrayList.add(new TestMsg(null,"测试222","2222",30,null));

        //mongoTemplate.insert(要插入的数据集, 要插入到的集合名)
        Collection myTest = mongoTemplate.insert(arrayList, "myTest");
        //返回的 myTest 就是插入的数据

        return myTest;
    }


    //更新指定数据
    public UpdateResult updateInfo(){
        Criteria criteria = Criteria.//配置查询条件,类似sql语句里面的 where 一系列语句
            where("username").is("LW1").
            and("moreTest").is("Test");

        Query query = Query.query(criteria);//生成查询语句
        //还可以用 query.addCriteria(Criteria对象) 额外加查询条件

        //把 username 的值修改为 LW5 ,把 moreTest 的值修改为 测试中
        Update update = Update.update("username", "LW5").set("moreTest", "测试中");

        //修改多条数据使用 updateMulti()
        //修改单条数据使用 updateFirst()
        //mongoTemplate.updateFirst(query对象, update对象, 查询结果对应的实体类.class,要操作的集合名);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, TestMsg.class,"myTest");//修改一条数据
        //此处返回的数据
        //{"matchedCount":1,"modifiedCount":1,"upsertedId":null}

        return updateResult;
    }

    //删除指定数据
    public DeleteResult removeInfo(){

        Criteria criteria = Criteria//配置查询条件
            .where("moreTest").is("测试中");

        Query query = new Query(criteria);//生成查询对象

        //mongoTemplate.remove(query对象,对应的实体类.class,要操作的集合名);
        DeleteResult remove = mongoTemplate.remove(query,TestMsg.class,"myTest");//执行删除语句

        return remove;
        //返回的数据 {"deletedCount":1}
    }


}




6、Controller层


package com.LW1.controller;

import com.LW1.dao.TestMsg;
import com.LW1.dao.TestMsg2;
import com.LW1.service.TestMongoDBService;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.List;

@Controller
public class TestMongoDBController {

    //获得服务类 TestMongoDBService
    @Autowired
    TestMongoDBService testMongoDBService;

    //创建集合
    @RequestMapping("/createTable")
    @ResponseBody
    public void createTable(){
        testMongoDBService.createTable();
    }

    //删除集合
    @RequestMapping("/deleteTable")
    @ResponseBody
    public void deleteTable(){
        testMongoDBService.deleteTable();
    }

    //查询所有数据
    @RequestMapping(value = "/selectAllInfo",method = RequestMethod.GET)
    @ResponseBody
    public List<TestMsg> selectAllInfo(){
        List<TestMsg> testMsg= testMongoDBService.selectAllInfo();
        return testMsg;
    }


    //按照条件查询数据
    @RequestMapping(value = "/selectInfo",method = RequestMethod.GET)
    @ResponseBody
    public List<TestMsg> selectInfoController(){
        List<TestMsg> testMsg = testMongoDBService.selectInfo();
        return testMsg;
    }


    //新增数据
    @RequestMapping(value = "/insertInfo",method = RequestMethod.GET)
    @ResponseBody
    public Collection insertInfoController(){
        Collection collection = testMongoDBService.insertInfo();
        return collection;
    }


    //修改指定数据
    @RequestMapping(value = "/updateInfo",method = RequestMethod.GET)
    @ResponseBody
    public UpdateResult updateInfoController(){
        UpdateResult updateResult = testMongoDBService.updateInfo();
        return updateResult;
    }


    //删除指定数据
    @RequestMapping(value = "/removeInfo",method = RequestMethod.GET)
    @ResponseBody
    public DeleteResult removeInfoController(){
        DeleteResult deleteResult = testMongoDBService.removeInfo();
        return deleteResult;
    }

}

7、Springboot 主程序代码


package com.LW1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.config.EnableMongoAuditing;

@SpringBootApplication
@EnableMongoAuditing //连接 MongoDB 数据库需要执行类添加 @EnableMongoAuditing 注解
public class TestMongoDbApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestMongoDbApplication.class, args);
    }

}