Introduction to Spring Data REST – Spring Data REST简介

最后修改: 2016年 3月 15日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This article will explain the basics of Spring Data REST and show how to use it to build a simple REST API.

本文将解释Spring Data REST的基础知识,并展示如何使用它来构建一个简单的REST API。

In general, Spring Data REST is built on top of the Spring Data project and makes it easy to build hypermedia-driven REST web services that connect to Spring Data repositories – all using HAL as the driving hypermedia type.

总的来说,Spring Data REST是建立在Spring Data项目之上的,它使建立超媒体驱动的REST网络服务变得容易,这些服务连接到Spring Data存储库–所有这些都使用HAL作为驱动超媒体类型。

It takes away a lot of the manual work usually associated with such tasks and makes implementing basic CRUD functionality for web applications quite simple.

它带走了许多通常与此类任务相关的手工工作,并使实现网络应用的基本CRUD功能变得相当简单。

2. Maven Dependencies

2.Maven的依赖性

The following Maven dependencies are required for our simple application:

我们的简单应用需要以下Maven依赖项。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</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-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

We decided to use Spring Boot for this example, but classic Spring will also work fine. We also chose to use the H2 embedded database in order to avoid any extra setup, but the example can be applied to any database.

我们决定在这个例子中使用Spring Boot,但经典的Spring也能正常工作。我们还选择了使用H2嵌入式数据库,以避免任何额外的设置,但这个例子也可以应用于任何数据库。

3. Writing the Application

3.编写应用程序

We will start by writing a domain object to represent a user of our website:

我们将首先编写一个域对象来代表我们网站的一个用户。

@Entity
public class WebsiteUser {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;
    private String email;

    // standard getters and setters
}

Every user has a name and an email, as well as an automatically-generated id. Now we can write a simple repository:

每个用户都有一个名字和一个电子邮件,以及一个自动生成的ID。现在我们可以编写一个简单的资源库。

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends PagingAndSortingRepository<WebsiteUser, Long> {
    List<WebsiteUser> findByName(@Param("name") String name);
}

This is an interface that allows you to perform various operations with WebsiteUser objects. We also defined a custom query that will provide a list of users based on a given name.

这是一个接口,允许你对WebsiteUser对象进行各种操作。我们还定义了一个自定义查询,它将提供一个基于给定名称的用户列表。

The @RepositoryRestResource annotation is optional and is used to customize the REST endpoint. If we decided to omit it, Spring would automatically create an endpoint at “/websiteUsers” instead of “/users“.

@RepositoryRestResource注解是可选的,用于定制REST端点。如果我们决定省略它,Spring会自动在”/websiteUsers“而不是”/users“创建一个端点。

Finally, we will write a standard Spring Boot main class to initialize the application:

最后,我们将编写一个标准的Spring Boot主类来初始化应用程序

@SpringBootApplication
public class SpringDataRestApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringDataRestApplication.class, args);
    }
}

That’s it! We now have a fully-functional REST API. Let’s take a look at it in action.

这就是了!我们现在有了一个功能齐全的REST API。让我们来看看它的运行情况。

4. Accessing the REST API

4.访问REST API

If we run the application and go to http://localhost:8080/ in a browser, we will receive the following JSON:

如果我们运行应用程序并在浏览器中进入http://localhost:8080/,我们将收到以下JSON。

{
  "_links" : {
    "users" : {
      "href" : "http://localhost:8080/users{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8080/profile"
    }
  }
}

As you can see, there is a “/users” endpoint available, and it already has the “?page“, “?size” and “?sort” options.

正如你所看到的,有一个”/users“端点可用,它已经有”?page“、”?size“和”? sort“选项。

There is also a standard “/profile” endpoint, which provides application metadata. It is important to note that the response is structured in a way that follows the constraints of the REST architecture style. Specifically, it provides a uniform interface and self-descriptive messages. This means that each message contains enough information to describe how to process the message.

还有一个标准的”/profile“端点,它提供应用程序元数据。需要注意的是,响应的结构是遵循REST架构风格的约束。具体来说,它提供了一个统一的接口和自我描述的消息。这意味着每个消息都包含足够的信息来描述如何处理该消息。

There are no users in our application yet, so going to http://localhost:8080/users would just show an empty list of users. Let’s use curl to add a user.

在我们的应用程序中还没有用户,所以到http://localhost:8080/users去,只会显示一个空的用户列表。让我们用curl来添加一个用户。

$ curl -i -X POST -H "Content-Type:application/json" -d '{  "name" : "Test", \ 
"email" : "test@test.com" }' http://localhost:8080/users
{
  "name" : "test",
  "email" : "test@test.com",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/1"
    },
    "websiteUser" : {
      "href" : "http://localhost:8080/users/1"
    }
  }
}

Lets take a look at the response headers as well:

让我们也来看看响应的标题。

HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Location: http://localhost:8080/users/1
Content-Type: application/hal+json;charset=UTF-8
Transfer-Encoding: chunked

You will notice that the returned content type is “application/hal+json“. HAL is a simple format that gives a consistent and easy way to hyperlink between resources in your API. The header also automatically contains the Location header, which is the address we can use to access the newly created user.

你会注意到,返回的内容类型是”application/hal+json“。HAL是一种简单的格式,它为你的API中的资源之间的超链接提供了一种一致且简单的方式。头部还自动包含Location头,这是我们可以用来访问新创建用户的地址。

We can now access this user at http://localhost:8080/users/1

我们现在可以在http://localhost:8080/users/1访问这个用户。

{
  "name" : "test",
  "email" : "test@test.com",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/1"
    },
    "websiteUser" : {
      "href" : "http://localhost:8080/users/1"
    }
  }
}

You can also use curl or any other REST client to issue PUT, PATCH, and DELETE requests. It also is important to note that Spring Data REST automatically follows the principles of HATEOAS. HATEOAS is one of the constraints of the REST architecture style, and it means that hypertext should be used to find your way through the API.

你也可以使用curl或任何其他REST客户端来发出PUT、PATCH和DELETE请求。还需要注意的是,Spring Data REST自动遵循HATEOAS的原则。HATEOAS是REST架构风格的约束之一,它意味着应该使用超文本在API中找到你的方式。

Finally, lets try to access the custom query that we wrote earlier and find all users with the name “test”. This is done by going to http://localhost:8080/users/search/findByName?name=test

最后,让我们尝试访问我们之前写的自定义查询,并找到所有名字为 “test “的用户。这是通过进入http://localhost:8080/users/search/findByName?name=test实现的。

{
  "_embedded" : {
    "users" : [ {
      "name" : "test",
      "email" : "test@test.com",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/users/1"
        },
        "websiteUser" : {
          "href" : "http://localhost:8080/users/1"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/search/findByName?name=test"
    }
  }
}

5. Conclusion

5.结论

This tutorial demonstrated the basics of creating a simple REST API with Spring Data REST. The example used in this article can be found in the linked GitHub project.

本教程演示了使用Spring Data REST创建一个简单的REST API的基础知识。本文中使用的示例可以在链接的GitHub项目中找到。