原创

Spring Boot集成mongodb快速入门demo

一、mongodb介绍

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,且与关系数据库的最为相像的。它支持的数据结构非常松散,是类似 json 的 bson 格式,因此可以存储比较复杂的数据类型。Mongo 最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

二、mongodb环境搭建

采用docker-compose搭建,配置文件如下

version: '3'

# 网桥mongo -> 方便相互通讯
networks:
  mongo:

services:
  # mongodb
  mongodb:
    image: registry.cn-hangzhou.aliyuncs.com/zhengqing/mongo:4.4.6  # 原镜像`mongo:4.4.6`
    restart: unless-stopped
    container_name: mongodb
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: 123456
      MONGO_DATA_DIR: /data/db
      MONGO_LOG_DIR: /data/logs
#    volumes:
#      - ./mongodb/db:/data/db
#      - ./mongodb/log:/data/log
    ports:
      - "27017:27017"
    networks:
      - mongo

  # 可视化图形工具
  adminmongo:
    image: mrvautin/adminmongo
    restart: unless-stopped
    container_name: adminmongo
    environment:
      - HOST=0.0.0.0
    depends_on:
      - 'mongodb'
    links:
      - mongodb
    ports:
      - "1234:1234"
    networks:
      - mongo

启动代码

docker-compose -f docker-compose-mongodb.yml -p mongodb up -d

访问地址:[`http://ip地址:1234`](http://127.0.0.1:1234)

Connection string:`mongodb://admin:123456@ip地址:27017`

三、代码工程

pom.xml

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>mongodb</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <!-- SpringBoot MongoDB -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>


    </dependencies>
</project>

entity

package com.et.mongodb.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.springframework.data.mongodb.core.mapping.MongoId;
import java.util.Date;

@Data
@ToString
@Accessors(chain = true)
public class User {

    /**
     * 使用 @MongoID 能更清晰的指定 _id 主键
     */
    @MongoId
    private String id;
    private String name;
    private String sex;
    private Integer salary;
    private Integer age;
    @JsonFormat( pattern ="yyyy-MM-dd", timezone ="GMT+8")
    private Date birthday;
    private String remake;
    private Status status;

}
package com.et.mongodb.entity;

import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

@Data
@ToString
@Accessors(chain = true)
public class Status {

    private Integer weight;
    private Integer height;

}

启动类

package com.et.mongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

属性文件application.yaml

server:
  port: 8088


spring:
  data:
    mongodb:
      uri: mongodb://admin:123456@127.0.0.1:27017/admin
      # 需要用户名和密码认证
      #uri:  mongodb://username:password@ip:port/admin

      #不需要用户名和密码认证
      #uri:  mongodb://ip:port/admin

代码仓库

四、测试

测试类

package com.et.mongodb;

import com.et.mongodb.entity.Status;
import com.et.mongodb.entity.User;
import com.mongodb.client.model.Indexes;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.Date;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class MongodbTests {
    private Logger log = LoggerFactory.getLogger(getClass());
    private static final String COLLECTION_NAME = "users";
    @Resource
    private MongoTemplate mongoTemplate;


    @Test
    public void createIndex() {
        String field = "name";
        // create index
        mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field));
    }
    @Test
    public void insert() {
        // set user info
        User user = new User()
                .setId("10")
                .setAge(22)
                .setSex("man")
                .setRemake("nothing")
                .setSalary(1500)
                .setName("zhangsan")
                .setBirthday(new Date())
                .setStatus(new Status().setHeight(180).setWeight(150));
        // insert user info,throw exception when the row record is exist
        User newUser = mongoTemplate.insert(user, COLLECTION_NAME);
        // output result
        log.info("user info:{}", newUser);
    }


}

86

五、参考

 

正文到此结束
该篇文章的评论功能已被站长关闭
Loading...