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完成的,这是个同步操作。为什么会出现这样的问题呢?这就是响应式编程的坑,如果你不理解就会出现问题。增删改查完了,但是没有页面展示,写一篇写页面。


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

查看所有标签

猜你喜欢:

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

Search User Interfaces

Search User Interfaces

Marti A. Hearst / Cambridge University Press / 2009-9-21 / USD 59.00

搜索引擎的本质是帮助用户更快、更方便、更有效地查找与获取所需信息。在不断改进搜索算法和提升性能(以技术为中心)的同时,关注用户的信息需求、搜寻行为、界面设计与交互模式是以用户为中心的一条并行发展思路。创新的搜索界面及其配套的交互机制对一项搜索服务的成功来说是至关重要的。Marti Hearst教授带来的这本新作《Search User Interfaces》即是后一条思路的研究成果,将信息检索与人......一起来看看 《Search User Interfaces》 这本书的介绍吧!

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具