Spring Boot MongoDB

Spring Boot MongoDB 入门实战

Posted by leone on 2019-01-12

Spring Boot MongoDB

开发环境

开发工具: Intellij IDEA 2018.2.6

springboot: 2.0.7.RELEASE

jdk: 1.8.0_192

maven: 3.6.0

mongoDB: 4.0.5

mongoDB 简介

什么是 mongoDB ?

MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

搭建项目

  • pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<groupId>com.andy</groupId>
<artifactId>spring-boot-mongodb</artifactId>
<version>1.0.7.RELEASE</version>
<modelVersion>4.0.0</modelVersion>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>Cairo-SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.0.3.RELEASE</version>
<configuration>
<!--<mainClass>${start-class}</mainClass>-->
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>
  • application.yml
1
2
3
4
5
6
7
8
9
10
server:
port: 8081

spring:
data:
mongodb:
uri: mongodb://localhost:27017/test
host: localhost
port: 27017
database: test
  • 启动类
1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* @author Leone
* @since 2018-05-09
**/
@SpringBootApplication
public class MongodbApplication {
public static void main(String[] args) {
SpringApplication.run(MongodbApplication.class, args);
}
}
  • MongoController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import com.andy.mongodb.entity.User;
import com.andy.mongodb.service.MongoService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
* <p>
*
* @author leone
* @since 2019-01-10
**/
@RestController
@RequestMapping("/api/mongo")
public class MongoController {

@Resource
private MongoService mongoService;


@PostMapping
public User save(@RequestBody User user) {
return mongoService.save(user);
}

@GetMapping("/list")
public List<User> list() {
return mongoService.list();
}


@GetMapping("/account")
public User findByName(@RequestParam("account") String account) {
return mongoService.findByName(account);
}

@PutMapping
public void update(@RequestBody User user) {
mongoService.update(user);
}

@DeleteMapping("/{userId}")
public void delete(@PathVariable("userId") Integer userId) {
mongoService.delete(userId);
}

}
  • User.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.andy.mongodb.entity;

import java.io.Serializable;
import java.util.Date;

/**
* <p>
*
* @author Leone
* @since 2018-01-24
**/
public class User implements Serializable {

private Long userId;

private String account;

private String password;

private String description;

private Integer age;

private Date createTime;

private boolean deleted;

public User() {
}

public User(Long userId, String account, String password, String description, Integer age, Date createTime, Boolean deleted) {
this.userId = userId;
this.account = account;
this.password = password;
this.description = description;
this.age = age;
this.createTime = createTime;
this.deleted = deleted;
}

public Long getUserId() {
return userId;
}

public void setUserId(Long userId) {
this.userId = userId;
}

public String getAccount() {
return account;
}

public void setAccount(String account) {
this.account = account;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public Integer getAge() {
return age;
}

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

public Date getCreateTime() {
return createTime;
}

public void setCreateTime(Date createTime) {
this.createTime = createTime;
}

public boolean isDeleted() {
return deleted;
}

public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
}
  • MongoService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.andy.mongodb.service;

import com.andy.mongodb.entity.User;
import com.mongodb.client.result.UpdateResult;
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.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* <p>
*
* @author leone
* @since 2019-01-10
**/
@Service
public class MongoService {

@Resource
private MongoTemplate mongoTemplate;


/**
* 新增
*
* @param user
* @return
*/
public User save(User user) {
mongoTemplate.save(user);
return user;
}


/**
* 列表
*
* @return
*/
public List<User> list() {
return mongoTemplate.findAll(User.class);
}


/**
* 根据名称查找
*
* @param account
* @return
*/
public User findByName(String account) {
Query query = new Query(Criteria.where("account").is(account));
return mongoTemplate.findOne(query, User.class);
}

/**
* 更新
*
* @param user
*/
public void update(User user) {
Query query = new Query(Criteria.where("userId").is(user.getUserId()));
Update update = new Update()
.set("description", user.getDescription())
.set("password", user.getPassword())
.set("age", user.getAge())
.set("deleted", user.isDeleted())
.set("createTime", user.getCreateTime())
.set("account", user.getAccount());
// 更新查询返回结果集的第一条
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, User.class);
// 更新查询返回结果集的所有
// mongoTemplate.updateMulti(query,update,User.class);
}


/**
* 删除
*
* @param userId
*/
public void delete(Integer userId) {
Query query = new Query(Criteria.where("userId").is(userId));
mongoTemplate.remove(query, User.class);
}


}

传送门