欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot整合MongoDB实现增删改查

程序员文章站 2022-05-07 12:44:09
...

1.编辑pom.xml, 增加依赖包

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-freemarker</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-mongodb</artifactId>
	</dependency>
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-lang3</artifactId>
		<version>3.4</version>
	</dependency>
	<dependency>
		<groupId>com.querydsl</groupId>
		<artifactId>querydsl-core</artifactId>
		<version>4.2.1</version>
	</dependency>
</dependencies>

2.编辑application.yml

spring:
    data:
        mongodb:
          uri: mongodb://admin:[email protected]:27017/test

3.添加UserDTO

public class UserDTO {
    @Id
    private String id;
    private String name;
    private String password;
    private int status;
    private Date createdAt;

    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password; }
    public int getStatus() { return status; }
    public void setStatus(int status) { this.status = status; }
    public Date getCreatedAt() { return createdAt; }
    public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; }
}

@Id注入后, 使用mongo自动生成的ID入库

4.添加UserService, 实现增删改查, 分页, 排序, 对象全更新

import com.smdb.demo.dto.UserDTO;
import com.smdb.demo.util.Pager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
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.querydsl.QPageRequest;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserService {
    // 自定义连接名称
    public static final String COLLECTION_NAME = "user";

    @Autowired
    private MongoTemplate mongoTemplate;

    public void add(UserDTO dto) {
        mongoTemplate.save(dto, COLLECTION_NAME);
    }

    public UserDTO get(String id) {
        Query query = new Query(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, UserDTO.class, COLLECTION_NAME);
    }

    public List<UserDTO> list(Pager pager, String name, int status) {
        Criteria criteria = new Criteria();
        if (StringUtils.isNotEmpty(name)) {
            criteria.and("name").regex(name);
        }
        if (status >= 0) {
            criteria.and("status").is(status);
        }
        Query query = new Query(criteria)
                .with(Sort.by(Sort.Order.desc("createdAt")))
                .with(new QPageRequest(pager.getPageIndex(), pager.getPageSize()));
        return mongoTemplate.find(query, UserDTO.class, COLLECTION_NAME);
    }

    public void update(UserDTO dto) {
        Query query = new Query(Criteria.where("id").is(dto.getId()));
        mongoTemplate.findAndReplace(query, dto, COLLECTION_NAME);
    }

    public void delete(String id) {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, UserDTO.class, COLLECTION_NAME);
    }
}

5.增加Controller

import com.smdb.demo.dto.UserDTO;
import com.smdb.demo.service.UserService;
import com.smdb.demo.util.JacksonUtils;
import com.smdb.demo.util.Pager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
public class IndexController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public String doFind(HttpServletRequest request) {
        String id = request.getParameter("id");
        UserDTO dto = userService.get(id);
        if (dto == null) {
            return error("用户不存在");
        }
        return JacksonUtils.compressObject(dto);
    }

    @RequestMapping(value = "/save", method = RequestMethod.GET)
    public String doSave(HttpServletRequest request) {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        UserDTO dto = new UserDTO();
        dto.setName(name);
        dto.setPassword(password);
        dto.setStatus(1);
        dto.setCreatedAt(new Date());
        userService.add(dto);
        return "success";
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String doList(HttpServletRequest request) {
        String name = request.getParameter("name");
        String statusStr = request.getParameter("status");
        int status = -1;
        if (StringUtils.isNotEmpty(statusStr)) {
            status = Integer.valueOf(statusStr);
        }
        String pageIndexStr = request.getParameter("pageIndex");
        String pageSizeStr = request.getParameter("pageSize");
        Pager pager = new Pager(0, 5);
        if (StringUtils.isNotEmpty(pageIndexStr)) {
            pager.setPageIndex(Integer.valueOf(pageIndexStr));
        }
        if (StringUtils.isNotEmpty(pageSizeStr)) {
            pager.setPageSize(Integer.valueOf(pageSizeStr));
        }
        return JacksonUtils.compressObject(userService.list(pager, name, status));
    }

    @RequestMapping(value = "/remove", method = RequestMethod.GET)
    public String doRemove(HttpServletRequest request) {
        String id = request.getParameter("id");
        UserDTO dto = userService.get(id);
        if (dto == null) {
            return error("用户不存在");
        }
        userService.delete(id);
        return success("操作成功");
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String doUpdate(HttpServletRequest request) {
        String id = request.getParameter("id");
        UserDTO dto = userService.get(id);
        if (dto == null) {
            return error("用户不存在");
        }
        String statusStr = request.getParameter("status");
        if (StringUtils.isNotEmpty(statusStr)) {
            dto.setStatus(Integer.valueOf(statusStr));
        }
        userService.update(dto);
        return JacksonUtils.compressObject(dto);
    }
}

6.测试各接口调用成功