十五、spring boot 2.x 集成 mongodb

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LDY1016/article/details/83586494

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

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

猜你喜欢

转载自blog.csdn.net/LDY1016/article/details/83586494