SpringBoot从入门到精通教程(二十一)- MongoDB集成用法

需求背景

Springboot集成:Mongodb实现

技术点

1. 集成mongodb依赖组件

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

2. 使用MongoTemplate对象(mongodb安装使用教程

@Resource
private MongoTemplate mongoTemplate;

代码演示

1. 项目目录结构

2. 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">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.md</groupId>
		<artifactId>spring-boot2-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<artifactId>spring-boot2-mongodb</artifactId>
	<packaging>jar</packaging>

	<name>spring-boot2-mongodb</name>
	<description>Spring Boot, MVC, Rest API for App</description>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<!-- 构建成可运行的Web项目 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib-ext-spring</artifactId>
		</dependency>
		<!-- mongodb集成 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

3. application.yml配置文件

spring:
   application:
      name: spring-boot-mongodb
   data:
      mongodb:
         uri: mongodb://127.0.0.1/demo
server:
   port: 9090

注意:这里使用的db库名为demo(mongodb安装使用教程

4. DemoDaoImpl.java文件

package com.md.demo.dao.impl;

import javax.annotation.Resource;

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.Component;

import com.md.demo.dao.DemoDao;
import com.md.demo.vo.DemoEntity;

@Component
public class DemoDaoImpl implements DemoDao {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void saveDemo(DemoEntity demoEntity) {
        mongoTemplate.save(demoEntity);
    }

    @Override
    public void removeDemo(DemoEntity demoEntity) {
        mongoTemplate.remove(demoEntity);
    }

    @Override
    public void updateDemo(DemoEntity demoEntity) {
        Query query = new Query(Criteria.where("id").is(demoEntity.getId()));

        Update update = new Update();
        update.set("title", demoEntity.getTitle());
        update.set("description", demoEntity.getDescription());
        update.set("by", demoEntity.getBy());
        update.set("url", demoEntity.getUrl());

        mongoTemplate.updateFirst(query, update, DemoEntity.class);
    }

    @Override
    public DemoEntity findDemoById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        DemoEntity demoEntity = mongoTemplate.findOne(query, DemoEntity.class);
        return demoEntity;
    }

}

5. DemoServiceImpl.java文件

package com.md.demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.md.demo.dao.DemoDao;
import com.md.demo.service.DemoService;
import com.md.demo.vo.DemoEntity;

@Service
public class DemoServiceImpl implements DemoService {

	@Autowired
	private DemoDao demoDao;

	@Override
	public void addDemo(DemoEntity demoEntity) {
		this.demoDao.saveDemo(demoEntity);
	}

	@Override
	public void removeDemo(Long id) {
		DemoEntity demoEntity = new DemoEntity();
		demoEntity.setId(id);
		this.demoDao.removeDemo(demoEntity);
	}

	@Override
	public void modifyDemo(DemoEntity demoEntity) {
		this.demoDao.updateDemo(demoEntity);
	}

	@Override
	public DemoEntity findDemoById(Long id) {
		return this.demoDao.findDemoById(id);
	}

}

案例演示

InitRest.java文件(添删查改)

package com.md.demo.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.md.demo.service.DemoService;
import com.md.demo.util.JsonResult;
import com.md.demo.util.ResultCode;
import com.md.demo.vo.DemoEntity;

/**
 * @author Minbo
 */
@RestController
public class InitRest {

	protected static Logger logger = LoggerFactory.getLogger(InitRest.class);

	/**
	 * http://localhost:9090/hello
	 * 
	 * @return
	 */
	@GetMapping("/hello")
	public String hello() {
		logger.info("hello");
		return "Hello greetings from spring-boot2-mongodb";
	}

	@Autowired
	private DemoService demoService;

	/**
	 * 新增
	 */
	@GetMapping("/saveDemoTest")
	public JsonResult saveDemoTest() {

		DemoEntity demoEntity = new DemoEntity();
		demoEntity.setId(1L);
		demoEntity.setTitle("使用mongodb");
		demoEntity.setDescription("这是描述");
		demoEntity.setBy("minbo");
		demoEntity.setUrl("https://blog.csdn.net/hemin1003");

		this.demoService.addDemo(demoEntity);

		demoEntity = new DemoEntity();
		demoEntity.setId(2L);
		demoEntity.setTitle("使用mongodb2");
		demoEntity.setDescription("这是描述2");
		demoEntity.setBy("minbo2");
		demoEntity.setUrl("https://blog.csdn.net/hemin1003");

		this.demoService.addDemo(demoEntity);

		return new JsonResult(ResultCode.SUCCESS);
	}

	/**
	 * 删除
	 */
	@GetMapping("/removeDemoTest")
	public JsonResult removeDemoTest(Long id) {
		this.demoService.removeDemo(id);

		return new JsonResult(ResultCode.SUCCESS);
	}

	/**
	 * 修改
	 */
	@GetMapping("/updateDemoTest")
	public JsonResult updateDemoTest() {

		DemoEntity demoEntity = new DemoEntity();
		demoEntity.setId(1L);
		demoEntity.setTitle("使用mongodb3");
		demoEntity.setDescription("这是描述3");
		demoEntity.setBy("minbo3");
		demoEntity.setUrl("https://blog.csdn.net/hemin1003");

		this.demoService.modifyDemo(demoEntity);

		return new JsonResult(ResultCode.SUCCESS, demoEntity);
	}

	/**
	 * 查找
	 */
	@GetMapping("/findDemoByIdTest")
	public JsonResult findDemoByIdTest(Long id) {
		DemoEntity demoEntity = this.demoService.findDemoById(id);
		System.out.println(demoEntity.toString());
		return new JsonResult(ResultCode.SUCCESS, demoEntity);
	}
}

例如:访问接口 http://localhost:9090/saveDemoTest

完整源码下载

我的Github源码地址:

https://github.com/hemin1003/spring-boot-study/tree/master/spring-boot2-study/spring-boot2-parent/spring-boot2-mongodb

该系列教程

SpringBoot系列

参考资料

mongodb java案例代码演示

mongodb安装使用教程

至此,全部介绍就结束了

------------------------------------------------------

------------------------------------------------------

关于我(个人域名)

我的开源项目集Github

期望和大家一起学习,一起成长,共勉,O(∩_∩)O谢谢

欢迎交流问题,可加个人QQ 469580884,

或者,加我的群号 751925591,一起探讨交流问题

不讲虚的,只做实干家

Talk is cheap,show me the code

发布了220 篇原创文章 · 获赞 232 · 访问量 65万+

猜你喜欢

转载自blog.csdn.net/hemin1003/article/details/99637830