Spring Boot MongoDB

欢迎来到 Spring Boot MongoDB示例. Spring Boot 是快速旋转一个 Spring 项目的最简单方式,而 MongoDB 是最受欢迎的 NoSQL 数据库。

春季启动 MongoDB

我们需要跟踪 API 才能使用 Spring Boot 和 MongoDB 数据库。

  • 春季数据 MongoDB
  • 春季启动

我们可以通过两种方法连接到MongoDB数据库,即MongoRepositoryMongoTemplate。我们将试图确定一个API提供的优点,以及你何时应该为你的使用案例选择任何一个API。

春季启动 MongoDB 项目设置

We will make use of Spring Initializr tool for quickly setting up the project. We will use just two dependencies as shown below: spring boot mongodb project setup using spring initializr Download the project and unzip it. Then import it into your favorite IDE - Eclipse or IntelliJ IDEA.

Maven 依赖

虽然我们已经完成了与该工具的安装,如果你想手动设置它,我们使用Maven构建系统这个项目,这里是我们使用的依赖:

 1<?xml version="1.0" encoding="UTF-8"?>
 2<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
 3    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4    <modelVersion>4.0.0</modelVersion>
 5
 6    <groupId>com.journaldev.spring</groupId>
 7    <artifactId>spring-boot-mongodb</artifactId>
 8    <version>0.0.1-SNAPSHOT</version>
 9    <packaging>jar</packaging>
10
11    <name>spring-boot-mongodb</name>
12    <description>Spring Boot MongoDB Example</description>
13
14    <parent>
15    	<groupId>org.springframework.boot</groupId>
16    	<artifactId>spring-boot-starter-parent</artifactId>
17    	<version>1.5.9.RELEASE</version>
18    	<relativePath /> <!-- lookup parent from repository -->
19    </parent>
20
21    <properties>
22    	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23    	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24    	<java.version>1.8</java.version>
25    </properties>
26
27    <dependencies>
28    	<dependency>
29    		<groupId>org.springframework.boot</groupId>
30    		<artifactId>spring-boot-starter-data-mongodb</artifactId>
31    	</dependency>
32    	<dependency>
33    		<groupId>org.springframework.boot</groupId>
34    		<artifactId>spring-boot-starter-web</artifactId>
35    	</dependency>
36
37    	<dependency>
38    		<groupId>org.springframework.boot</groupId>
39    		<artifactId>spring-boot-starter-test</artifactId>
40    		<scope>test</scope>
41    	</dependency>
42    </dependencies>
43
44    <build>
45    	<plugins>
46    		<plugin>
47    			<groupId>org.springframework.boot</groupId>
48    			<artifactId>spring-boot-maven-plugin</artifactId>
49    		</plugin>
50    	</plugins>
51    </build>
52</project>

请确保从 maven 中心使用稳定版本的 Spring Boot

春季启动 MongoDB 模型类

我们有一个简单的模型类别User.java

 1package com.journaldev.bootifulmongodb.model;
 2
 3import java.util.Date;
 4import java.util.HashMap;
 5import java.util.Map;
 6
 7import org.springframework.data.annotation.Id;
 8import org.springframework.data.mongodb.core.mapping.Document;
 9
10@Document
11public class User {
12
13    @Id
14    private String userId;
15    private String name;
16    private Date creationDate = new Date();
17    private Map<String, String> userSettings = new HashMap<>();
18
19    public String getUserId() {
20    	return userId;
21    }
22
23    public void setUserId(String userId) {
24    	this.userId = userId;
25    }
26
27    public String getName() {
28    	return name;
29    }
30
31    public void setName(String name) {
32    	this.name = name;
33    }
34
35    public Date getCreationDate() {
36    	return creationDate;
37    }
38
39    public void setCreationDate(Date creationDate) {
40    	this.creationDate = creationDate;
41    }
42
43    public Map<String, String> getUserSettings() {
44    	return userSettings;
45    }
46
47    public void setUserSettings(Map<String, String> userSettings) {
48    	this.userSettings = userSettings;
49    }
50}

春天启动 MongoDB API

我们将在我们的应用程序中跟踪功能和数据库交互。

  • 获取所有用户
  • 获取具有 ID 的用户
  • 获取用户设置
  • 获取地图 中的特定密钥* 添加/更新用户设置

春季数据 MongoDB - MongoRepository

现在我们将使用Spring Data MongoDB存储库来访问我们的数据。Spring Data MongoRepository为我们提供了常见的功能,我们可以轻松插入并使用它。

 1package com.journaldev.bootifulmongodb.dal;
 2
 3import org.springframework.data.mongodb.repository.MongoRepository;
 4import org.springframework.stereotype.Repository;
 5
 6import com.journaldev.bootifulmongodb.model.User;
 7
 8@Repository
 9public interface UserRepository extends MongoRepository<User, String> {
10}

定义 MongoDB 属性

在我们放置控制器之前,重要的是我们将连接到MongoDB的本地实例,我们将使用Spring Boot属性来做到这一点。

 1#Local MongoDB config
 2spring.data.mongodb.authentication-database=admin
 3spring.data.mongodb.username=root
 4spring.data.mongodb.password=root
 5spring.data.mongodb.database=user_db
 6spring.data.mongodb.port=27017
 7spring.data.mongodb.host=localhost
 8
 9# App config
10server.port=8102
11spring.application.name=BootMongo
12server.context-path=/user

因此,应用程序将运行在端口8102上,并连接到提供授权的本地mongoDB实例. 如果您有一个未启用授权的本地实例,您可以简单地删除最初的三个配置行。

春节控制器的定义

最后,让我们来做我们的控制器类。

 1package com.journaldev.bootifulmongodb.controller;
 2
 3import java.util.List;
 4
 5import org.slf4j.Logger;
 6import org.slf4j.LoggerFactory;
 7import org.springframework.web.bind.annotation.PathVariable;
 8import org.springframework.web.bind.annotation.RequestBody;
 9import org.springframework.web.bind.annotation.RequestMapping;
10import org.springframework.web.bind.annotation.RequestMethod;
11import org.springframework.web.bind.annotation.RestController;
12
13import com.journaldev.bootifulmongodb.dal.UserRepository;
14import com.journaldev.bootifulmongodb.model.User;
15
16@RestController
17@RequestMapping(value = "/")
18public class UserController {
19
20    private final Logger LOG = LoggerFactory.getLogger(getClass());
21
22    private final UserRepository userRepository;
23
24    public UserController(UserRepository userRepository) {
25    	this.userRepository = userRepository;
26    }
27}

我们只是 [Autowired]( / 社区 / 教程 / 春天-autowired - 注释)存储器界面依赖,我们将使用以下。

定义 APIs

对于我们提到的功能,我们现在将创建API并访问用户存储器依赖性,该依赖性将内部使用Spring Data MongoRepository API。

获取所有用户

1@RequestMapping(value = "", method = RequestMethod.GET)
2public List<User> getAllUsers() {
3    LOG.info("Getting all users.");
4    return userRepository.findAll();
5}

findAll()只是 Spring Data MongoRepository 内部提供的一种方法。

通过ID获取用户

现在,让我们获得一个具有ID的特定用户。

1@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
2public User getUser(@PathVariable String userId) {
3    LOG.info("Getting user with ID: {}.", userId);
4    return userRepository.findOne(userId);
5}

findOne()只是 Spring Data MongoRepository 内部提供的一种方法,用一个 ID 获取一个对象。

添加新用户

我们将在下面的功能中添加一个新用户。

1@RequestMapping(value = "/create", method = RequestMethod.POST)
2public User addNewUsers(@RequestBody User user) {
3    LOG.info("Saving user.");
4    return userRepository.save(user);
5}

获得用户设置

现在我们已将样本数据添加到DB中,让我们尝试提取其中的一部分。

1@RequestMapping(value = "/settings/{userId}", method = RequestMethod.GET)
2public Object getAllUserSettings(@PathVariable String userId) {
3    User user = userRepository.findOne(userId);
4    if (user != null) {
5    	return user.getUserSettings();
6    } else {
7    	return "User not found.";
8    }
9}

获取特定用户设置

1@RequestMapping(value = "/settings/{userId}/{key}", method = RequestMethod.GET)
2public String getUserSetting(@PathVariable String userId, @PathVariable String key) {
3    User user = userRepository.findOne(userId);
4    if (user != null) {
5    	return user.getUserSettings().get(key);
6    } else {
7    	return "User not found.";
8    }
9}

注意在上面的查询中,我们得到了用户对象,然后提取了完整的设置地图(可能包含1000个对象),最后得到了自己的值。

添加新用户设置

让我们尝试为现有用户添加一些数据:

 1@RequestMapping(value = "/settings/{userId}/{key}/{value}", method = RequestMethod.GET)
 2public String addUserSetting(@PathVariable String userId, @PathVariable String key, @PathVariable String value) {
 3    User user = userRepository.findOne(userId);
 4    if (user != null) {
 5    	user.getUserSettings().put(key, value);
 6    	userRepository.save(user);
 7    	return "Key added";
 8    } else {
 9    	return "User not found.";
10    }
11}

随着我们写的所有代码,很明显,我们不需要写一行代码来访问数据库,除了定义存储界面和自动化依赖性之外,这是 Spring Data MongoRepository API 提供的便利性,但它也有一些缺点。

春季数据 MongoDB - MongoTemplate

我们将在这里定义MongoTemplate数据库查询. 使用MongoTemplate,您将看到我们对我们查询的内容和结果中包含的数据有更为细微的控制。

定义 DAL 界面

要在数据库访问层中提供合同,我们将首先定义一个与我们的 Spring Data 内置方法相似的界面。

 1package com.journaldev.bootifulmongodb.dal;
 2
 3import java.util.List;
 4
 5import com.journaldev.bootifulmongodb.model.User;
 6
 7public interface UserDAL {
 8
 9    List<User> getAllUsers();
10
11    User getUserById(String userId);
12
13    User addNewUser(User user);
14
15    Object getAllUserSettings(String userId);
16
17    String getUserSetting(String userId, String key);
18
19    String addUserSetting(String userId, String key, String value);
20}

使用 DAL 接口

让我们继续前进并定义这些方法。

 1package com.journaldev.bootifulmongodb.dal;
 2
 3import java.util.List;
 4
 5import org.springframework.beans.factory.annotation.Autowired;
 6import org.springframework.data.mongodb.core.MongoTemplate;
 7import org.springframework.data.mongodb.core.query.Criteria;
 8import org.springframework.data.mongodb.core.query.Query;
 9import org.springframework.stereotype.Repository;
10
11import com.journaldev.bootifulmongodb.model.User;
12
13@Repository
14public class UserDALImpl implements UserDAL {
15
16    @Autowired
17    private MongoTemplate mongoTemplate;
18
19    @Override
20    public List<User> getAllUsers() {
21    	return mongoTemplate.findAll(User.class);
22    }
23
24    @Override
25    public User getUserById(String userId) {
26    	Query query = new Query();
27    	query.addCriteria(Criteria.where("userId").is(userId));
28    	return mongoTemplate.findOne(query, User.class);
29    }
30
31    @Override
32    public User addNewUser(User user) {
33    	mongoTemplate.save(user);
34    	// Now, user object will contain the ID as well
35    	return user;
36    }
37
38    @Override
39    public Object getAllUserSettings(String userId) {
40    	Query query = new Query();
41    	query.addCriteria(Criteria.where("userId").is(userId));
42    	User user = mongoTemplate.findOne(query, User.class);
43    	return user != null ? user.getUserSettings() : "User not found.";
44    }
45
46    @Override
47    public String getUserSetting(String userId, String key) {
48    	Query query = new Query();
49    	query.fields().include("userSettings");
50    	query.addCriteria(Criteria.where("userId").is(userId).andOperator(Criteria.where("userSettings." + key).exists(true)));
51    	User user = mongoTemplate.findOne(query, User.class);
52    	return user != null ? user.getUserSettings().get(key) : "Not found.";
53    }
54
55    @Override
56    public String addUserSetting(String userId, String key, String value) {
57    	Query query = new Query();
58    	query.addCriteria(Criteria.where("userId").is(userId));
59    	User user = mongoTemplate.findOne(query, User.class);
60    	if (user != null) {
61    		user.getUserSettings().put(key, value);
62    		mongoTemplate.save(user);
63    		return "Key added.";
64    	} else {
65    		return "User not found.";
66    	}
67    }
68}

上面的类中的方法实现是使用MongoTemplate依赖性。 看看getUserById(...)方法是如何接收用户的。 我们构建了一个查询并通过了所需的参数。 您更感兴趣的是getUserSetting查询。 让我们了解上面发生了什么:

  • 我们构建了查询的标准,以检查平等性
  • 包括方法包括在从DB中提取时结果应该包含的字段名称. 这意味着,在这种情况下,用户设置密钥将被提取,这将节省大量的数据被提取,而不是必要的
  • 此外,我们询问了用户和地图密钥。

春季数据 MongoDB 测试运行

我们可以简单地使用一个命令来运行这个应用程序:

1mvn spring-boot:run

一旦应用程序运行,我们可以尝试使用此API来保存新用户:

1https://localhost:8102/user/create

由于这将是一个 POST 请求,我们也将发送 JSON 数据:

1{
2  "name" : "Shubham",
3  "userSettings" : {
4    "bike" : "pulsar"
5  }
6}

当我们返回蒙古答案时,我们会得到这样的东西:

1{
2  "userId": "5a5f28cc3178058b0fafe1dd",
3  "name": "Shubham",
4  "creationDate": 1516165830856,
5  "userSettings": {
6    "bike" : "pulsar"
7  }
8}

Spring Data MongoDB MongoRepository Example Create You can get all users by using the API as GET request:

1https://localhost:8102/user/

我们会得到像这样的东西回来:

 1[
 2  {
 3    "userId": "5a5f28cc3178058b0fafe1dd",
 4    "name": "Shubham",
 5    "creationDate": 1516165830856,
 6    "userSettings": {
 7      "bike" : "pulsar"
 8    }
 9  }
10]

Spring Data MongoDB If you see above UserController class, we haven't hooked up MongoTemplate to be used. Below code snippet shows the changes required to use MongoTemplate for reading user settings.

 1//define Data Access Layer object
 2private final UserDAL userDAL;
 3
 4//initialize DAL object via constructor autowiring
 5public UserController(UserRepository userRepository, UserDAL userDAL) {
 6    this.userRepository = userRepository;
 7    this.userDAL = userDAL;
 8}
 9
10//change method implementation to use DAL and hence MongoTemplate
11@RequestMapping(value = "/settings/{userId}", method = RequestMethod.GET)
12public Object getAllUserSettings(@PathVariable String userId) {
13    User user = userRepository.findOne(userId);
14    if (user != null) {
15        return userDAL.getAllUserSettings(userId);
16    } else {
17        return "User not found.";
18    }
19}
20
21//change method implementation to use DAL and hence MongoTemplate
22@RequestMapping(value = "/settings/{userId}/{key}", method = RequestMethod.GET)
23public String getUserSetting(
24        @PathVariable String userId, @PathVariable String key) {
25    return userDAL.getUserSetting(userId, key);
26}

Restart the app and run scenarios to get all user settings and to get any specific key. Below image shows the output from Postman app. Spring Data MongoDB MongoTemplate example Spring Data MongoDB MongoTemplate example criteria query

MongoTemplate 对 MongoRepository

  • MongoTemplate在查询数据和从数据库中提取哪些数据时提供了更大的控制权
  • Spring Data 存储库为我们提供了如何获取数据的方便视角
  • MongoTemplate 依赖数据库。这意味着使用 Spring Data 存储库,您可以轻松切换到完全不同的数据库,只需使用不同的 Spring Data 存储库用于 MySQL 或 Neo4J 或其他任何东西。

春天启动 MongoDB 简介

在本课中,我们研究了MongoTemplate如何为我们提供更多对春季数据存储库的控制,但在涉及更深层次的查询时也可能有点复杂。所以,这完全是你在开发你的想法时要选什么。 请自由留下评论。 下载从下面链接的源代码。 请确保在运行提供的应用程序之前更改MongoDB凭据。

(下载 Spring Boot MongoDB 示例项目)

Published At
Categories with 技术
comments powered by Disqus