前面通过 5 节的内容,我们学习了 mongodb 的使用,这节我们通过学过的知识运用 springboot 整合 mongodb 搭建一个小项目。
springboot 基于 maven 项目搭建的具体过程这里就不再赘述了,首先来看下 pom 文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.infogroupId>
<artifactId>spring-mongoartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>spring-mongoname>
<description>spring-mongodescription>
<properties>
<java.version>1.8java.version>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASEspring-boot.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-mongodbartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-validationartifactId>
dependency>
dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-dependenciesartifactId>
<version>${spring-boot.version}version>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.1version>
<configuration>
<source>1.8source>
<target>1.8target>
<encoding>UTF-8encoding>
configuration>
plugin>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<version>2.3.7.RELEASEversion>
<configuration>
<mainClass>com.info.springmongo.SpringMongoApplicationmainClass>
configuration>
<executions>
<execution>
<id>repackageid>
<goals>
<goal>repackagegoal>
goals>
execution>
executions>
plugin>
plugins>
build>
project>
整合 mongodb 只需要一个依赖 spring-boot-starter-data-mongodb
,接下来看下 yml 文件关于 mongodb 的配置。
spring:
application:
name: spring-mongo
data:
mongodb:
uri: mongodb://账号:密码@192.168.227.128:27017/student
与 mongodb 交互可以使用 MongoRepository
,这时一个类似 jap 的一个接口,我们的 dao 层只需要继承它就可以直接调用很多方法,也可以使用 MongoTemplate
来完成,这里选择第二种方式来实现。
看一下 service 层的代码:
package com.info.springmongo.service.impl;
import com.info.springmongo.entity.Student;
import com.info.springmongo.service.StudentService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
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.Service;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
@Service
public class StudentServiceImpl implements StudentService {
private final MongoTemplate mongoTemplate;
private AtomicLong currentId = new AtomicLong(0);
public StudentServiceImpl(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
@PostConstruct
public void loadCurrentId() {
GroupOperation operation = Aggregation.group("id").last("id").as("maxId");
TypedAggregation<Student> aggregation = Aggregation.newAggregation(Student.class, operation);
Long maxId = mongoTemplate.aggregate(aggregation, Student.class)
.getMappedResults()
.stream()
.max(Comparator.comparing(Student::getId))
.map(Student::getId).orElse(0L);
currentId = new AtomicLong(new AtomicLong(maxId).incrementAndGet());
}
@Override
public int save(Student student) {
student.setTimeOfEnrollment(LocalDateTime.now());
student.setId(currentId.getAndIncrement());
mongoTemplate.insert(student);
return 1;
}
@Override
public int update(Student student) {
Query query = new Query(Criteria.where("_id").is(student.getId()));
Update update = new Update().set("name", student.getName());
try {
mongoTemplate.updateFirst(query, update, Student.class);
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
@Override
public Student getById(Long id) {
Query query = new Query(Criteria.where("_id").is(id));
return mongoTemplate.findOne(query, Student.class);
}
@Override
public List<Student> getList(Student student) {
if (student == null) {
return mongoTemplate.findAll(Student.class)
.stream()
.limit(10)
.collect(Collectors.toList());
}
Query query = new Query();
if (student.getId() != null) {
query.addCriteria(Criteria.where("_id").is(student.getId()));
}
if (!StringUtils.isEmpty(student.getName())) {
query.addCriteria(Criteria.where("name").regex("^.*" + student.getName() + ".$"));
}
if (student.getAge() != null) {
query.addCriteria(Criteria.where("age").is(student.getAge()));
}
if (student.getTimeOfEnrollment() != null) {
query.addCriteria(Criteria.where("timeOfEnrollment").lte(student.getTimeOfEnrollment()));
}
return mongoTemplate.find(query, Student.class)
.stream()
.limit(10)
.collect(Collectors.toList());
}
@Override
public List<Student> listByPage(Student student, int pageNum, int pageSize) {
int beginPage = pageNum > 0 ? (pageNum - 1) * pageSize : 0;
Query query = new Query();
if (student.getId() != null) {
query.addCriteria(Criteria.where("_id").is(student.getId()));
}
if (!StringUtils.isEmpty(student.getName())) {
query.addCriteria(Criteria.where("name").regex("^.*" + student.getName() + ".$"));
}
if (student.getAge() != null) {
query.addCriteria(Criteria.where("age").is(student.getAge()));
}
if (student.getTimeOfEnrollment() != null) {
query.addCriteria(Criteria.where("timeOfEnrollment").lte(student.getTimeOfEnrollment()));
}
return mongoTemplate.find(query, Student.class)
.stream()
.skip(beginPage)
.limit(pageSize)
.collect(Collectors.toList());
}
@Override
public int delete(Long id) {
Query query = new Query(Criteria.where("_id").is(id));
mongoTemplate.findAndRemove(query, Student.class);
return 1;
}
}
controller 层代码如下:
package com.info.springmongo.controller;
import com.info.springmongo.common.ResultCode;
import com.info.springmongo.dto.PageStudentDTO;
import com.info.springmongo.dto.StudentDTO;
import com.info.springmongo.entity.Student;
import com.info.springmongo.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/stu")
public class StudentController {
private final StudentService studentService;
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
@PostMapping("/")
public ResultCode saveStu(@Validated @RequestBody StudentDTO student) {
Student stu = new Student();
BeanUtils.copyProperties(student, stu);
studentService.save(stu);
return ResultCode.success();
}
@PutMapping("/{id}")
public ResultCode updateStu(@Validated @RequestBody StudentDTO student, @PathVariable("id") Long id) {
Student stu = new Student();
BeanUtils.copyProperties(student, stu);
stu.setId(id);
studentService.update(stu);
return ResultCode.success();
}
@DeleteMapping("/{id}")
public ResultCode deleteStu(@PathVariable("id") Long id) {
studentService.delete(id);
return ResultCode.success();
}
@GetMapping("/")
public ResultCode listStu(StudentDTO student) {
Student stu = new Student();
if (student == null) {
stu = null;
} else {
BeanUtils.copyProperties(student, stu);
}
return ResultCode.success(studentService.getList(stu));
}
@GetMapping("/page")
public ResultCode listByPageStu(@RequestBody PageStudentDTO student) {
Student stu = new Student();
BeanUtils.copyProperties(student, stu);
return ResultCode.success(studentService.listByPage(stu, student.getPageNumber(), student.getPageSize()));
}
}
撸完代码就可以开测了,postman 跑起来,这里的代码比较简单,我也就不做说明了,后面我会把代码上传到 代码仓库,感兴趣的可以拉下来看看。
代码不是重点,下节我们将用这份代码在我们的 docker
环境上把代码跑起来,我们下节见。