WebFlux 集成MongoDb

栏目: 数据库 · 发布时间: 6年前

内容简介:上一篇文章中我们已经简单搭建了webflux的框架,今天就集成mongodb完成一个用户管理系统。到bin目录下打开cmd命令窗口 运行:

上一篇文章中我们已经简单搭建了webflux的框架,今天就集成 mongodb 完成一个用户管理系统。

1. 安装MongoDb

  • 直接去官网下载安装包:

https://www.mongodb.com/downl...

  • 选择对应的操作系统,我的是windows,然后选择zip,还是msi。我下载的zip也就是绿色免安装。如果msi的就直接下一步,下一步按要求安装就好了。
  • zip启动方式:

到bin目录下打开cmd命令窗口 运行:

mongod.exe --dbpath C:\Tools\mongodb\db

dbpathshi 是设置数据备份目录,必须要设置,否则启动不了。

bin目录下的 mongo.exe 是mongodb的查询客户端,可以执行查询操作。一些查询命令可以直接去官网看。

show dbs :显示当前所有文档库,相当于数据库

use test :选择test库

db.user.find() :查询所有user文档数据

db.user.drop() :删除所有user文档

2.集成mogodb

pom文件依赖:

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

配置连接:

spring.data.mongodb.host=localhost
spring.data.mongodb.database=test
spring.data.mongodb.port=27017

3.dao层

package com.mike.dao;

import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;

import com.mike.po.User;

/**
 * The class UserDao.java
 */
@Repository
public interface UserDao extends ReactiveMongoRepository<User, String>{

}

ReactiveMongoRepository 已经帮你实现了增删该查,如果需要别的方法,需要自己添加实现接口。具体写法和JPA类似

4.service层

package com.mike.service;

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.stereotype.Service;

import com.mike.dao.UserDao;
import com.mike.po.User;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * The class UserService.java
 */
@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    
    @Autowired
    private MongoTemplate mongoTemplate;
    
    public Mono<User> saveOrUpdateUser(User user){
        return userDao.save(user);
    }
    
    public Mono<User> findById(String id){
        return userDao.findById(id);
    }
    
    public Flux<User> findAll(){
        return userDao.findAll();
    }
    
    public  void deleteById(String id){
        // 使用mongoTemplate来做删除   直接使用提供的删除方法不行
        Query query = Query.query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, User.class);
        //userDao.deleteById(id);  这样无法删除,不知道为什么
    }
}

5.controller层

package com.mike.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;

import com.mike.po.User;
import com.mike.service.UserService;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * The class UserController.java
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    
    @PostMapping("/user")
    public String save(User user,final Model model){
         Mono<User> u = userService.saveOrUpdateUser(user);
         model.addAttribute("user", u);
         return "redirect:/users";
    }
    
    @GetMapping("/user/find/{id}")
    @ResponseBody
    public Mono<User> find(@PathVariable("id") String id){
        return userService.findById(id);
    }
    
    @GetMapping("/users")
    public String findAll(final Model model){
        Flux<User> users= userService.findAll();
        model.addAttribute("users", users);
        return "user";
    }
    
    @GetMapping("/user/delete/{id}")
    public String delete(@PathVariable("id") String id){
        userService.deleteById(id);
        return "redirect:/users";
    }
}

6.po层

package com.mike.po;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Field;

/**
 * The class User.java
 */
public class User {
    @Id
    @Field("_id")
    private String id;
    private String name;
    private String sex;
    private String job;
    private String address;
    private String phone;
    
    
    /**
     * @return the id
     */
    public String getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the sex
     */
    public String getSex() {
        return sex;
    }
    /**
     * @param sex the sex to set
     */
    public void setSex(String sex) {
        this.sex = sex;
    }
    /**
     * @return the job
     */
    public String getJob() {
        return job;
    }
    /**
     * @param job the job to set
     */
    public void setJob(String job) {
        this.job = job;
    }
    /**
     * @return the address
     */
    public String getAddress() {
        return address;
    }
    /**
     * @param address the address to set
     */
    public void setAddress(String address) {
        this.address = address;
    }
    /**
     * @return the phone
     */
    public String getPhone() {
        return phone;
    }
    /**
     * @param phone the phone to set
     */
    public void setPhone(String phone) {
        this.phone = phone;
    }
    
    
}

7. 总结

和正常的关系型数据库的操作一样,只不过有些问题想不明白。我上面的删除旧出现了无法删除的问题,最后使用的mongodbTemplate完成的,这是个同步操作。为什么会出现这样的问题呢?这就是响应式编程的坑,如果你不理解就会出现问题。增删改查完了,但是没有页面展示,写一篇写页面。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Computer Age Statistical Inference

Computer Age Statistical Inference

Bradley Efron、Trevor Hastie / Cambridge University Press / 2016-7-21 / USD 74.99

The twenty-first century has seen a breathtaking expansion of statistical methodology, both in scope and in influence. 'Big data', 'data science', and 'machine learning' have become familiar terms in ......一起来看看 《Computer Age Statistical Inference》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具