Accessing MongoDB Data with REST

This guide walks you through the process of creating an application that accesses document-based data through a hypermedia-based RESTful front end.
What You Will Build

You will build a Spring application that lets you create and retrieve Person objects stored in a MongoDB NoSQL database by using Spring Data REST. Spring Data REST takes the features of Spring HATEOAS and Spring Data MongoDB and automatically combines them together.
Spring Data REST also supports Spring Data JPA, Spring Data Gemfire, and Spring Data Neo4j as backend data stores, but those are not part of this guide.
What You need

About 15 minutes

A favorite text editor or IDE

JDK 1.8 or later

Gradle 4+ or Maven 3.2+

You can also import the code straight into your IDE:

    Spring Tool Suite (STS)

    IntelliJ IDEA

How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To start from scratch, move on to Starting with Spring Initializr.

To skip the basics, do the following:

Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-accessing-mongodb-data-rest.git

cd into gs-accessing-mongodb-data-rest/initial

Jump ahead to Install and launch MongoDB.

When you finish, you can check your results against the code in gs-accessing-mongodb-data-rest/complete.
Starting with Spring Initializr

For all Spring applications, you should start with the Spring Initializr. The Initializr offers a fast way to pull in all the dependencies you need for an application and does a lot of the set up for you. This example needs the Rest Repositories and Spring Data MongoDB dependencies. The following image shows the Initializr set up for this sample project:
initializr
The preceding image shows the Initializr with Maven chosen as the build tool. You can also use Gradle. It also shows values of com.example and accessing-mongodb-data-rest as the Group and Artifact, respectively. You will use those values throughout the rest of this sample.

The following listing shows the pom.xml file created when you choose Maven:

<?xml version="1.0" encoding="UTF-8"?>


4.0.0

org.springframework.boot
spring-boot-starter-parent
2.2.2.RELEASE


com.example
accessing-mongodb-data-rest
0.0.1-SNAPSHOT
accessing-mongodb-data-rest
Demo project for Spring Boot

<properties>
	<java.version>1.8</java.version>
</properties>

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

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
		<exclusions>
			<exclusion>
				<groupId>org.junit.vintage</groupId>
				<artifactId>junit-vintage-engine</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
</dependencies>

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>

The following listing shows the build.gradle file created when you choose Gradle:

plugins {
id ‘org.springframework.boot’ version ‘2.2.2.RELEASE’
id ‘io.spring.dependency-management’ version ‘1.0.8.RELEASE’
id ‘java’
}

group = ‘com.example’
version = ‘0.0.1-SNAPSHOT’
sourceCompatibility = ‘1.8’

repositories {
mavenCentral()
}

dependencies {
implementation ‘org.springframework.boot:spring-boot-starter-data-mongodb’
implementation ‘org.springframework.boot:spring-boot-starter-data-rest’
testImplementation(‘org.springframework.boot:spring-boot-starter-test’) {
exclude group: ‘org.junit.vintage’, module: ‘junit-vintage-engine’
}
}

test {
useJUnitPlatform()
}

Install and launch MongoDB

For this guide to work, you must stand up a local MongoDB server.

On a Mac OS X machine with Homebrew installed, run the following command:

brew install mongodb

You can find more installation options at https://docs.mongodb.org/manual/installation/.

After installing MongoDB, you need to launch the mongo daemon. On a Mac, you can use the following command:

$ mongod
all output going to: /usr/local/var/log/mongodb/mongo.log

You can start the MongoDB client from another terminal window by running the mongo command.
Create a Domain Object

Create a new domain object to present a person, as the following example (in src/main/java/com/example/accessingmongodbdatarest/Person.java) shows:

package com.example.accessingmongodbdatarest;

import org.springframework.data.annotation.Id;

public class Person {

@Id private String id;

private String firstName;
private String lastName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}
}

The Person object has a first name and a last name. (There is also an ID object, which is configured to be automatically generated, so need not deal with it.)
Create a Person Repository

Next, you need to create a simple repository, as the following listing (in src/main/java/com/example/accessingmongodbdatarest/PersonRepository.java) shows:

package com.example.accessingmongodbdatarest;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = “people”, path = “people”)
public interface PersonRepository extends MongoRepository<Person, String> {

List findByLastName(@Param(“name”) String name);

}

This repository is an interface and lets you perform various operations that involve Person objects. It gets these operations by extending MongoRepository, which in turn extends the PagingAndSortingRepository interface defined in Spring Data Commons.

At runtime, Spring Data REST automatically creates an implementation of this interface. Then it uses the @RepositoryRestResource annotation to direct Spring MVC to create RESTful endpoints at /people.
@RepositoryRestResource is not required for a repository to be exported. It is used only to change the export details, such as using /people instead of the default value of /persons.

Here you have also defined a custom query to retrieve a list of Person objects based on the lastName value. You can see how to invoke it further down in this guide.
By default, Spring Boot tries to connect to a locally hosted instance of MongoDB. Read the reference docs for how to point your application to an instance of MongoDB that is hosted elsewhere.

@SpringBootApplication is a convenience annotation that adds all of the following:

@Configuration: Tags the class as a source of bean definitions for the application context.

@EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.

@ComponentScan: Tells Spring to look for other components, configurations, and services in the com/example package, letting it find the controllers.

The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there was not a single line of XML? There is no web.xml file, either. This web application is 100% pure Java and you did not have to deal with configuring any plumbing or infrastructure.
Build an executable JAR

You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

If you use Gradle, you can run the application by using ./gradlew bootRun. Alternatively, you can build the JAR file by using ./gradlew build and then run the JAR file, as follows:

java -jar build/libs/gs-accessing-mongodb-data-rest-0.1.0.jar

If you use Maven, you can run the application by using ./mvnw spring-boot:run. Alternatively, you can build the JAR file with ./mvnw clean package and then run the JAR file, as follows:

java -jar target/gs-accessing-mongodb-data-rest-0.1.0.jar

The steps described here create a runnable JAR. You can also build a classic WAR file.

Logging output is displayed. The service should be up and running within a few seconds.
Test the Application

Now that the application is running, you can test it. You can use any REST client you wish. The following examples use the *nix tool curl.

First you want to see the top level service, as the following example shows:

$ curl http://localhost:8080
{
“_links” : {
“people” : {
“href” : “http://localhost:8080/people{?page,size,sort}”,
“templated” : true
}
}
}

The preceding example provides a first glimpse of what this server has to offer. There is a people link located at http://localhost:8080/people. It has some options, such as ?page, ?size, and ?sort.
Spring Data REST uses the HAL format for JSON output. It is flexible and offers a convenient way to supply links adjacent to the data that is served.

When you use the people link, you see the Person records in the database (none at present):

$ curl http://localhost:8080/people
{
“_links” : {
“self” : {
“href” : “http://localhost:8080/people{?page,size,sort}”,
“templated” : true
},
“search” : {
“href” : “http://localhost:8080/people/search”
}
},
“page” : {
“size” : 20,
“totalElements” : 0,
“totalPages” : 0,
“number” : 0
}
}

There are currently no elements and, hence, no pages. It is time to create a new Person!
If you run this guide multiple times, there may be leftover data. Refer to the MongoDB shell quick reference for commands to find and drop your database if you need a fresh start.

The following command creats a person named “Frodo Baggins”:

$ curl -i -X POST -H “Content-Type:application/json” -d “{ “firstName” : “Frodo”, “lastName” : “Baggins” }” http://localhost:8080/people
HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Location: http://localhost:8080/people/53149b8e3004990b1af9f229
Content-Length: 0
Date: Mon, 03 Mar 2014 15:08:46 GMT

-i: Ensures you can see the response message including the headers. The URI of the newly created Person is shown.

-X POST: Signals this a POST used to create a new entry.

-H "Content-Type:application/json": Sets the content type so the application knows the payload contains a JSON object.

-d '{ "firstName" : "Frodo", "lastName" : "Baggins" }': Is the data being sent.

Notice how the previous POST operation includes a Location header. This contains the URI of the newly created resource. Spring Data REST also has two methods (RepositoryRestConfiguration.setReturnBodyOnCreate(…) and setReturnBodyOnUpdate(…)) that you can use to configure the framework to immediately return the representation of the resource just created/updated.

From this you can query for all people, as the following example shows:

$ curl http://localhost:8080/people
{
“_links” : {
“self” : {
“href” : “http://localhost:8080/people{?page,size,sort}”,
“templated” : true
},
“search” : {
“href” : “http://localhost:8080/people/search”
}
},
“_embedded” : {
“persons” : [ {
“firstName” : “Frodo”,
“lastName” : “Baggins”,
“_links” : {
“self” : {
“href” : “http://localhost:8080/people/53149b8e3004990b1af9f229”
}
}
} ]
},
“page” : {
“size” : 20,
“totalElements” : 1,
“totalPages” : 1,
“number” : 0
}
}

The persons object contains a list with Frodo. Notice how it includes a self link. Spring Data REST also uses the Evo Inflector to pluralize the names of entities for groupings.

You can directly query for the individual record, as the following example shows:

$ curl http://localhost:8080/people/53149b8e3004990b1af9f229
{
“firstName” : “Frodo”,
“lastName” : “Baggins”,
“_links” : {
“self” : {
“href” : “http://localhost:8080/people/53149b8e3004990b1af9f229”
}
}
}

This might appear to be purely web-based, but, behind the scenes, it is talking to the MongoDB database you started.

In this guide, there is only one domain object. With a more complex system, where domain objects are related to each other, Spring Data REST renders additional links to help navigate to connected records.

Find all the custom queries, as the following example shows:

$ curl http://localhost:8080/people/search
{
“_links” : {
“findByLastName” : {
“href” : “http://localhost:8080/people/search/findByLastName{?name}”,
“templated” : true
}
}
}

You can see the URL for the query, including the HTTP query parameter, name. This matches the @Param(“name”) annotation embedded in the interface.

To use the findByLastName query, run the following command:

$ curl http://localhost:8080/people/search/findByLastName?name=Baggins
{
“_embedded” : {
“persons” : [ {
“firstName” : “Frodo”,
“lastName” : “Baggins”,
“_links” : {
“self” : {
“href” : “http://localhost:8080/people/53149b8e3004990b1af9f229”
}
}
} ]
}
}

Because you defined it to return List in the code, it returns all of the results. If you had defined it to return only Person, it picks one of the Person objects to return. Since this can be unpredictable, you probably do not want to do that for queries that can return multiple entries.

You can also issue PUT, PATCH, and DELETE REST calls to replace, update, or delete existing records, respectively. The following example uses a PUT call:

$ curl -X PUT -H “Content-Type:application/json” -d “{ “firstName”: “Bilbo”, “lastName”: “Baggins” }” http://localhost:8080/people/53149b8e3004990b1af9f229
$ curl http://localhost:8080/people/53149b8e3004990b1af9f229
{
“firstName” : “Bilbo”,
“lastName” : “Baggins”,
“_links” : {
“self” : {
“href” : “http://localhost:8080/people/53149b8e3004990b1af9f229”
}
}
}

The following example uses a PATCH call:

$ curl -X PATCH -H “Content-Type:application/json” -d “{ “firstName”: “Bilbo Jr.” }” http://localhost:8080/people/53149b8e3004990b1af9f229
$ curl http://localhost:8080/people/53149b8e3004990b1af9f229
{
“firstName” : “Bilbo Jr.”,
“lastName” : “Baggins”,
“_links” : {
“self” : {
“href” : “http://localhost:8080/people/53149b8e3004990b1af9f229”
}
}
}

PUT replaces an entire record. Fields not supplied will be replaced with null. You can use PATCH to update a subset of items.

You can also delete records, as the following example shows:

$ curl -X DELETE http://localhost:8080/people/53149b8e3004990b1af9f229
$ curl http://localhost:8080/people
{
“_links” : {
“self” : {
“href” : “http://localhost:8080/people{?page,size,sort}”,
“templated” : true
},
“search” : {
“href” : “http://localhost:8080/people/search”
}
},
“page” : {
“size” : 20,
“totalElements” : 0,
“totalPages” : 0,
“number” : 0
}
}

A convenient aspect of this hypermedia-driven interface is how you can discover all the RESTful endpoints by using curl (or whatever REST client you like). There is no need to exchange a formal contract or interface document with your customers.
Summary

Congratulations! You have just developed an application with a hypermedia-based REST front end and a MongoDB-based back end.

translate:
翻译:

本指南将引导您完成创建应用程序的过程,该应用程序通过基于超媒体的RESTful前端访问基于文档的数据。

你将建造什么

您将构建一个Spring应用程序,它允许您使用Spring Data REST创建和检索存储在MongoDB NoSQL数据库中的Person对象。Spring Data REST采用了Spring HATEOAS和Spring Data MongoDB的特性,并将它们自动组合在一起。

Spring Data REST还支持Spring Data JPA、Spring Data Gemfire和Spring Data Neo4j作为后端数据存储,但这些不是本指南的一部分。

你需要什么
大约15分钟
最喜欢的文本编辑器或IDE
JDK 1.8或更高版本
Gradle 4+或Maven 3.2+
您还可以直接将代码导入到IDE中:
Spring工具套件(STS)
智力观念
如何完成本指南
与大多数Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。不管怎样,你最终都会使用代码。
要从头开始,请继续使用Spring初始化器。
要跳过基本步骤,请执行以下操作:
下载并解压缩此指南的源存储库,或者使用Git克隆它:Git clone https://github.com/spring-guides/gs-accessing-mongodb-data-rest.Git
cd进入gs访问mongodb数据rest/initial
继续安装并启动MongoDB。
完成后,可以对照gs中访问mongodb data rest/complete的代码检查结果。
从Spring初始化器开始
对于所有Spring应用程序,都应该从Spring初始化器开始。initializer提供了一种快速的方法来获取应用程序所需的所有依赖项,并为您进行了很多设置。本例需要Rest存储库和Spring数据MongoDB依赖项。下图显示了为此示例项目设置的初始值设定项:
初始化程序

上图显示了选择Maven作为构建工具的初始化器。你也可以用格雷德。它还分别显示com.example和访问mongodb数据rest作为组和工件的值。您将在本示例的其余部分中使用这些值。

发布了0 篇原创文章 · 获赞 152 · 访问量 7049

猜你喜欢

转载自blog.csdn.net/blog_programb/article/details/105237860