MongoDB个人基础教程(三)springboot mongoDB整合demo篇

环境: dubbo + zookeeper + springboot

  1. 引入pom
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-mongodb</artifactId>
 </dependency>
  1. 配置连接信息
spring:
    data:
        mongodb:
          uri: mongodb://localhost:27017/test
  1. pojo类
package com.skindow.pojo;

import java.io.Serializable;

public class User implements Serializable{
    private static final long serialVersionUID = -3977379600503324407L;
    private Integer id;

    private String name;

    private Integer age;

    private String address;

    private String country;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country == null ? null : country.trim();
    }
}
  1. 新建接口 MongoUserService
package com.skindow.MongoDBService;

import com.skindow.pojo.User;

/**
 * Created by Administrator on 2019/8/30.
 */
public interface MongoUserService {
    /** 保存用户
     * @param user 用户对象
     * @param collectionName 集合名称
     */
    public void saveUser(User user, String collectionName) throws Exception;

    /** 通过名称查询用户
     * @param name 用户名称
     * @param collectionName 集合名称
     * @return
     */
    public User findUserByName(String name,String collectionName) throws Exception;


    /**更新对象 用过id进行更新
     * @param user 必传id
     * @param collectionName 集合名称
     * @throws Exception
     */
    public void updateTest(User user,String collectionName) throws Exception;

    /** 通过id 名称进行删除
     * @param id 用户id
     * @param colliectionName 集合名称
     */
    public void deleteTestById(Integer id,String colliectionName) throws Exception;
    
}

  1. 提供者实现类MongoUserDao
package com.skindow.mongoDao;

import com.skindow.MongoDBService.MongoUserService;
import com.skindow.pojo.User;
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.Component;

/**
 * Created by Administrator on 2019/8/30.
 */
@Component
public class MongoUserDao implements MongoUserService{
    @Autowired
    private MongoTemplate mongoTemplate;

    /** 保存用户
     * @param user 用户对象
     * @param collectionName 集合名称
     */
    public void saveUser(User user,String collectionName) throws Exception {
        if (user == null)
        {
            throw new Exception("user is null");
        }
         mongoTemplate.save(user,collectionName);
    }

    /** 通过名称查询用户
     * @param name 用户名称
     * @param collectionName 集合名称
     * @return
     */
    public User findUserByName(String name,String collectionName) throws Exception {
        if (name == null || name.isEmpty())
        {
            throw new Exception("user is empty");
        }
        Query query=new Query(Criteria.where("name").is(name));
        User user = mongoTemplate.findOne(query,User.class,collectionName);
        return user;
    }

    /**更新对象 用过id进行更新
     * @param user 必传id
     * @param collectionName 集合名称
     * @throws Exception
     */
    public void updateTest(User user,String collectionName) throws Exception {
        if (user == null  || user.getId() == null)
        {
            throw new Exception("user is null or id is null");
        }
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update();
        if (user.getAge() != null)
        {
            update.set("age", user.getAge());
        }
        if (user.getAge() != null)
        {
           update.set("age", user.getAge());
        }
        if (user.getAddress() != null)
        {
            update.set("address",user.getAddress());
        }
        if (user.getCountry() != null)
        {
            update.set("country",user.getCountry());
        }
        mongoTemplate.updateFirst(query, update, User.class,collectionName);
    }

    /** 通过id 名称进行删除
     * @param id 用户id
     * @param colliectionName 集合名称
     */
    public void deleteTestById(Integer id,String colliectionName) throws Exception {
        if (id == null)
        {
            throw new Exception("id is null");
        }
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, User.class, colliectionName);
    }

}

<bean id="MongoUserService" class="com.skindow.mongoDao.MongoUserDao"/>
	<dubbo:service interface="com.skindow.MongoDBService.MongoUserService" ref="MongoUserService" version="1.0.0" timeout="10000" retries="0"/>

  1. 控制层MongoUserController
package com.skindow.controller;

import com.skindow.MongoDBService.MongoUserService;
import com.skindow.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * Created by Administrator on 2019/8/30.
 */
@Controller
@Slf4j
@RequestMapping("/mongo/user")
@Api("mongo-user")
public class MongoUserController {
    @Autowired
    private MongoUserService mongoUserService;

    @RequestMapping(value = "/insertUser",method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "添加用户", consumes = "application/json")
    @ResponseBody
    public String insertUser(@RequestBody User user, @RequestParam(value="collectionName",required = false) String collectionName)
    {
        if (null == user)
        {
            return "user is null!";
        }
        try {
            mongoUserService.saveUser(user,collectionName);
        } catch (Exception e) {
            log.error("mongoUserService.saveUser error {}",e);
            return "error";
        }
        return "success";
    }
    @RequestMapping(value = "/findUserByName",method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "查找用户", consumes = "application/json")
    @ResponseBody
    public User findUserByName(@RequestParam("name") String name,@RequestParam(value="collectionName",required = false) String collectionName)
    {
        User user = null;
        try {
            user =  mongoUserService.findUserByName(name,collectionName);
        } catch (Exception e) {
            log.error("mongoUserService.findUserByName error {}",e);
            return null;
        }
        return user;
    }
    @RequestMapping(value = "/updateUser",method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "修改用户", consumes = "application/json")
    @ResponseBody
    public String updateUser(@RequestBody User user, @RequestParam(value="collectionName",required = false) String collectionName)
    {
        try {
            mongoUserService.updateUser(user,collectionName);
        } catch (Exception e) {
            log.error("mongoUserService.updateUser error {}",e);
            return "error";
        }
        return "success";
    }
    @RequestMapping(value = "/deleteTestById",method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "删除用户", consumes = "application/json")
    @ResponseBody
    public String deleteTestById(@RequestParam("id")Integer id,@RequestParam(value="collectionName",required = false) String collectionName){
        try {
            mongoUserService.deleteTestById(id,collectionName);
        } catch (Exception e) {
            log.error("mongoUserService.deleteTestById error {}",e);
            return "error";
        }
        return "success";
    }
}

<dubbo:reference id="MongoUserService" check="false" interface="com.skindow.MongoDBService.MongoUserService" version="1.0.0" timeout="10000" retries="0"/>

  1. 测试
    这里我们使用swagger2进行测试
    添加用户
    在这里插入图片描述
    在这里插入图片描述
    插入成功
    查找用户
    在这里插入图片描述
项目地址 对应tag createMongoDBDemo
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值