SpringBoot专题

SpringBoot入门建站全系列(二十六)Mongodb非关系

2019-10-08  本文已影响0人  逍遥天扬

SpringBoot入门建站全系列(二十六)Mongodb非关系型数据库的使用

一、概述

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

关系型数据库最典型的数据结构是表,由二维表及其之间的联系所组成的一个数据组织

优点:

缺点:

非关系型数据库严格上不是一种数据库,应该是一种数据结构化存储方法的集合,可以是文档或者键值对等。

优点:

缺点:

代码可以在SpringBoot组件化构建https://www.pomit.cn/java/spring/springboot.html中的MongoDb组件中查看,并下载。

首发地址:
品茗IT-同步发布

如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以加入我们的java学习圈,点击即可加入,共同学习,节约学习时间,减少很多在学习中遇到的难题。

二、配置

本文假设你已经引入spring-boot-starter-web。已经是个SpringBoot项目了,如果不会搭建,可以打开这篇文章看一看《SpringBoot入门建站全系列(一)项目建立》

2.1 Maven依赖

使用mongodb需要引入spring-boot-starter-data-mongodb。

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

2.2 配置文件

在application.properties 中需要配置mongodb的信息,如:

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

我这里只有一个mongodb的配置:

三、方式一:MongoRepository操作MongoDb

我们直接新建接口,继承MongoRepository接口, 这样一切都会变的特别简单。类似于Spring-data-jpa的写法。

3.1 数据库DAO

DAO中可以按照Spring-data的常规写法自定义查询方法,也可以直接使用MongoRepository定义好的方法。

UserAddationDao:

package com.cff.springbootwork.mongodb.dao;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.cff.springbootwork.mongodb.model.User;

public interface UserAddationDao extends MongoRepository<User, Long> {
    User findByName(String name);
}

注意,实体User要用@Id指明id

3.2 业务逻辑层

我们直接调用UserAddationDao来做一些增删改查。

UserAddationService:

package com.cff.springbootwork.mongodb.service;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cff.springbootwork.mongodb.dao.UserAddationDao;
import com.cff.springbootwork.mongodb.model.User;

/**
 * 第一种方式
 * 
 * @author fufei
 *
 */
@Service
public class UserAddationService {
    private static final Logger logger = LoggerFactory.getLogger(UserAddationService.class);
    @Autowired
    private UserAddationDao userAddationDao;

    /**
     * 保存对象
     *
     * @param book
     * @return
     */
    public String save(User user) {
        logger.info("--------------------->[MongoDB save start]");
        user.setRegisterTime(new Date());
        userAddationDao.save(user);
        return "添加成功";
    }

    /**
     * 查询所有
     *
     * @return
     */
    public List<User> findAll() {
        logger.info("--------------------->[MongoDB find start]");
        return userAddationDao.findAll();
    }

    /***
     * 根据id查询
     * 
     * @param id
     * @return
     */
    public User getUserById(Long id) {
        logger.info("--------------------->[MongoDB find start]");
        return userAddationDao.findById(id).orElse(null);
    }

    /**
     * 根据名称查询
     *
     * @param name
     * @return
     */
    public User getUserByName(String name) {
        logger.info("--------------------->[MongoDB find start]");
        return userAddationDao.findByName(name);
    }

    /**
     * 更新对象
     *
     * @param book
     * @return
     */
    public String update(User user) {
        logger.info("--------------------->[MongoDB update start]");
        userAddationDao.save(user);
        return "success";
    }

    /***
     * 删除对象
     * 
     * @param book
     * @return
     */
    public String deleteUser(User user) {
        logger.info("--------------------->[MongoDB delete start]");
        userAddationDao.delete(user);
        return "success";
    }
}

3.3 测试

MongodbAddationRest:

package com.cff.springbootwork.mongodb.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cff.springbootwork.mongodb.model.User;
import com.cff.springbootwork.mongodb.service.UserAddationService;

@RestController
@RequestMapping("/mongo2")
public class MongodbAddationRest {
    @Autowired
    UserAddationService userService;

    @PostMapping("/save")
    public String saveObj(@RequestBody User user) {
        return userService.save(user);
    }

    @GetMapping("/findAll")
    public List<User> findAll() {
        return userService.findAll();
    }

    @GetMapping("/findOne")
    public User findOne(@RequestParam Long id) {
        return userService.getUserById(id);
    }

    @GetMapping("/findOneByName")
    public User findOneByName(@RequestParam String name) {
        return userService.getUserByName(name);
    }

    @PostMapping("/update")
    public String update(@RequestBody User user) {
        User existUser = userService.getUserById(user.getId());
        if (existUser == null) {
            existUser = user;
        } else {
            if (user.getAge() != null) {
                existUser.setAge(user.getAge());
            }

            if (user.getPassword() != null) {
                existUser.setPassword(user.getPassword());
            }

            if (user.getName() != null) {
                existUser.setName(user.getName());
            }

            if (user.getPhone() != null) {
                existUser.setPhone(user.getPhone());
            }

            if (user.getRegisterTime() != null) {
                existUser.setRegisterTime(user.getRegisterTime());
            }

            if (user.getUsername() != null) {
                existUser.setUsername(user.getUsername());
            }
        }

        return userService.update(existUser);
    }

    @PostMapping("/delOne")
    public String delOne(@RequestBody User user) {
        return userService.deleteUser(user);
    }
}

四、方式二:MongoTemplate操作MongoDb

4.1 直接在业务逻辑中调用MongoTemplate

UserService:

package com.cff.springbootwork.mongodb.service;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 com.cff.springbootwork.mongodb.model.User;

/**
 * 第一种方式
 * @author fufei
 *
 */
@Service
public class UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存对象
     *
     * @param book
     * @return
     */
    public String save(User user) {
        logger.info("--------------------->[MongoDB save start]");
        user.setRegisterTime(new Date());
        mongoTemplate.save(user);
        return "添加成功";
    }

    /**
     * 查询所有
     *
     * @return
     */
    public List<User> findAll() {
        logger.info("--------------------->[MongoDB find start]");
        return mongoTemplate.findAll(User.class);
    }

    /***
     * 根据id查询
     * 
     * @param id
     * @return
     */
    public User getUserById(Long id) {
        logger.info("--------------------->[MongoDB find start]");
        Query query = new Query(Criteria.where("_id").is(id));
        return mongoTemplate.findOne(query, User.class);
    }

    /**
     * 根据名称查询
     *
     * @param name
     * @return
     */
    public User getUserByName(String name) {
        logger.info("--------------------->[MongoDB find start]");
        Query query = new Query(Criteria.where("name").is(name));
        return mongoTemplate.findOne(query, User.class);
    }

    /**
     * 更新对象
     *
     * @param book
     * @return
     */
    public String update(User user) {
        logger.info("--------------------->[MongoDB update start]");
        Query query = new Query(Criteria.where("_id").is(user.getId()));
        Update update = new Update().set("password", user.getPassword()).set("age", user.getAge()).set("phone",
                user.getPhone());
        // updateFirst 更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query, update, User.class);
        return "success";
    }

    /***
     * 删除对象
     * 
     * @param book
     * @return
     */
    public String deleteUser(User user) {
        logger.info("--------------------->[MongoDB delete start]");
        mongoTemplate.remove(user);
        return "success";
    }
}

4.2 测试

MongodbRest:

package com.cff.springbootwork.mongodb.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cff.springbootwork.mongodb.model.User;
import com.cff.springbootwork.mongodb.service.UserService;

@RestController
@RequestMapping("/mongo")
public class MongodbRest {
    @Autowired
    UserService userService;

    @PostMapping("/save")
    public String saveObj(@RequestBody User user) {
        return userService.save(user);
    }

    @GetMapping("/findAll")
    public List<User> findAll() {
        return userService.findAll();
    }

    @GetMapping("/findOne")
    public User findOne(@RequestParam Long id) {
        return userService.getUserById(id);
    }

    @GetMapping("/findOneByName")
    public User findOneByName(@RequestParam String name) {
        return userService.getUserByName(name);
    }

    @PostMapping("/update")
    public String update(@RequestBody User user) {
        return userService.update(user);
    }

    @PostMapping("/delOne")
    public String delOne(@RequestBody User user) {
        return userService.deleteUser(user);
    }
}

五、过程中用到的实体

User:


详细完整的代码,可以访问品茗IT-博客《SpringBoot入门建站全系列(二十六)Mongodb非关系型数据库的使用》进行查看

品茗IT-博客专题:https://www.pomit.cn/lecture.html汇总了Spring专题Springboot专题SpringCloud专题web基础配置专题。

快速构建项目

Spring项目快速开发工具:

一键快速构建Spring项目工具

一键快速构建SpringBoot项目工具

一键快速构建SpringCloud项目工具

一站式Springboot项目生成

Mysql一键生成Mybatis注解Mapper

Spring组件化构建

SpringBoot组件化构建

SpringCloud服务化构建

喜欢这篇文章么,喜欢就加入我们一起讨论SpringBoot使用吧!


品茗IT交流群
上一篇 下一篇

猜你喜欢

热点阅读