spring boot 集成 mongodb

mongodb安装请查看:http://www.runoob.com/mongodb/mongodb-window-install.html

1、在pom.xml中添加mongodb的maven依赖

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

2、在application.properties文件中添加mongodb的配置

#mongodb
spring.data.mongodb.uri=mongodb://localhost:27017/demo
#设置了密码的话使用下面的配置方式
#spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/dbName

或者

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=demo
# 默认没有账号密码
#spring.data.mongodb.username=
#spring.data.mongodb.password=

3、编写实体类:MongoUserEntity.java

package com.ldy.bootv2.demo.entity;

import java.io.Serializable;

import org.springframework.data.annotation.Id;

public class MongoUserEntity implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	private String id;

	private String userName;

	private Integer userAge;

	public String getId() {
		return id;
	}

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

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Integer getUserAge() {
		return userAge;
	}

	public void setUserAge(Integer userAge) {
		this.userAge = userAge;
	}

}

4、编写dao层:MongoUserRepository.java

package com.ldy.bootv2.demo.dao;

import java.util.List;

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

import com.ldy.bootv2.demo.entity.MongoUserEntity;

public interface MongoUserRepository extends MongoRepository<MongoUserEntity, String> {

    List<MongoUserEntity> findByUserName(String userName);

}

5、编写测试接口:MongoUserController.java

package com.ldy.bootv2.demo.controller;

import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ldy.bootv2.demo.dao.MongoUserRepository;
import com.ldy.bootv2.demo.entity.MongoUserEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "mongo用户信息管理接口-API")
@RestController
@RequestMapping("/mongoUser")
public class MongoUserController {

	private static Logger logger = LoggerFactory.getLogger(MongoUserController.class);

	@Autowired
	MongoUserRepository mongoUserRepository;

	@GetMapping("/findAll")
	@ApiOperation("查询全部用户")
	public List<MongoUserEntity> findAll() {
		logger.info("您调用了findAll接口");
		return mongoUserRepository.findAll();
	}

	@GetMapping("/findByUserName")
	@ApiOperation("根据用户名查询用户")
	public List<MongoUserEntity> findByUserName(
			@ApiParam(value = "用户名", required = true) @RequestParam String userName) {
		logger.info("您调用了findByUserName接口");
		return mongoUserRepository.findByUserName(userName);
	}

	@GetMapping("/getOne/{id}")
	@ApiOperation("根据ID查询用户")
	public MongoUserEntity getOne(@ApiParam(value = "用户id", required = true) @PathVariable("id") String id) {
		logger.info("您调用了getOne接口");
		Optional<MongoUserEntity> optional = mongoUserRepository.findById(id);
		return optional.get();
	}

	@PutMapping("/saveOrUpdate")
	@ApiOperation("新增或者修改用户")
	public String saveOrUpdate(@ModelAttribute MongoUserEntity entity) {
		logger.info("您调用了saveOrUpdate接口");
		try {
			if (null == entity.getId()) {
				mongoUserRepository.insert(entity);
			} else {
				mongoUserRepository.save(entity);
			}

		} catch (Exception e) {
			logger.error("失败,原因:" + e.getMessage());
			return "error";
		}
		return "success";
	}

	@DeleteMapping("/delete/{id}")
	@ApiOperation("根据ID删除用户")
	public String deleteById(@ApiParam(value = "用户id", required = true) @PathVariable("id") String id) {
		logger.info("您调用了delete接口");
		try {
			mongoUserRepository.deleteById(id);
		} catch (Exception e) {
			logger.error("失败,原因:" + e.getMessage());
			return "error";
		}
		return "success";
	}

}

6、运行项目,打开swagger页面,测试接口正常,swagger的集成请查看:https://blog.csdn.net/LDY1016/article/details/83415640

源码下载地址:https://pan.baidu.com/s/1Z771VDiuabDBJJV445xLeA#list/path=%2Fspring%20boot%202.x%20%E4%BB%A3%E7%A0%81

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值