Spring Data REST quickly builds restful api applications, no longer have to worry about overtime

Spring Data REST quickly build restful api applications

What is Spring Data REST

Spring Data REST is based on the Spring Data repository, which can automatically output the repository as a REST resource. Currently, it supports the automatic conversion of Spring Data JPA, Spring Data MongoDB, Spring Data Neo4j, Spring Data GemFire, and Spring Data Cassandra repositories into REST services. Attention is automatic. To put it simply, Spring Data REST automates a large number of REST template interfaces that we need to write.

restful api

REST is a design style (unrelated to a specific language) whose URL body is a resource, which is a noun. And it only supports the HTTP protocol, which stipulates the use of HTTP Method to express the actions to be done this time, and the types generally do not exceed the four or five types. These actions express the only ways in which resources can be transformed.

There are five commonly used HTTP verbs (the corresponding SQL commands are in parentheses).

  • GET (SELECT): Retrieve resource(s) from the server.
  • POST (CREATE): Create a new resource on the server.
  • PUT (UPDATE): Update the resource on the server (the client provides the complete resource after the change).
  • PATCH (UPDATE): Update the resource on the server (client provides changed properties).
  • DELETE (DELETE): Deletes the resource from the server.
  • HEAD: Get metadata of the resource.
  • OPTIONS: Get information about which properties of the resource can be changed by the client.

accomplish

Spring Boot 2.0.0.RELEASE

add dependencies

pom.xml

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

define domain

package com.zyndev.springdatarestdemo.domain;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

/**
 * @author 张瑀楠 [email protected]
 * @version 0.0.1
 */
@Data
@Entity
@Table(name = "tb_user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;            // 用户id
    private String userName;    // 用户名称
    private String password;    // 用户密码
    private Integer active;     // 是否可用
    private Date lastLoginTime; // 最后登录时间
    private Date createTime;    // 账户创建时间
    private Date updateTime;    // 最后更新时间
}

Define Repository

package com.zyndev.springdatarestdemo.controller;

import com.zyndev.springdatarestdemo.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

/**
 * @author 张瑀楠 [email protected]
 * @version 0.0.1
 */
@RepositoryRestResource(path="user")
public interface UserRepository extends JpaRepository<User, Long> {
}

configure

server:
  port: 8080

spring:
  jpa:
    hibernate:
      ddl-auto: update

Automatically create tables by setting spring.jpa.hibernate.ddl-auto=update. If you have already built a table according to the domain, you can ignore it. The configuration of the database is omitted in the configuration. Please add it according to the situation.

test

Startup project:

1. GET access to localhost:8080/user
Here I have added a piece of data

{
    "_embedded": {
        "users": [
            {
                "userName": "abc",
                "password": "abc",
                "active": 1,
                "lastLoginTime": null,
                "createTime": null,
                "updateTime": null,
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/user/1" },
                    "user": {
                        "href": "http://localhost:8080/user/1" }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/user{?page,size,sort}",
            "templated": true
        },
        "profile": {
            "href": "http://localhost:8080/profile/user"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 1,
        "totalPages": 1,
        "number": 0
    }
}

2. GET access localhost:8080/user/1

It can be seen from the above 1that there is

{
    "userName": "abc",
    "password": "abc",
    "active": 1,
    "lastLoginTime": null,
    "createTime": null,
    "updateTime": null,
    "_links": {
        "self": {
            "href": "http://localhost:8080/user/1"
        },
        "user": {
            "href": "http://localhost:8080/user/1"
        }
    }
}

3. GET access localhost:8080/user/2

Because 2does not exist, then return404

4. POST localhost:8080/user to create a resource

set upContent-Type=application/json

body:

{
    "userName": "abcdfasdfe",
    "password": "abc",
    "active": 1,
    "lastLoginTime": null,
    "createTime": null,
    "updateTime": null
}

return status code201

Return data:

{
    "userName": "abcdfasdfe",
    "password": "abc",
    "active": 1,
    "lastLoginTime": null,
    "createTime": null,
    "updateTime": null,
    "_links": {
        "self": {
            "href": "http://localhost:8080/user/4"
        },
        "user": {
            "href": "http://localhost:8080/user/4"
        }
    }
}

5. Visit GET again and visit localhost:8080/user

At this time, it can be seen that the number of users is 2, indicating that the creation has been successful.

{
    "_embedded": {
        "users": [
            {
                "userName": "abc",
                "password": "abc",
                "active": 1,
                "lastLoginTime": null,
                "createTime": null,
                "updateTime": null,
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/user/1" },
                    "user": {
                        "href": "http://localhost:8080/user/1" }
                }
            },
            {
                "userName": "abcdfasdfe",
                "password": "abc",
                "active": 1,
                "lastLoginTime": null,
                "createTime": null,
                "updateTime": null,
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/user/4" },
                    "user": {
                        "href": "http://localhost:8080/user/4" }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/user{?page,size,sort}",
            "templated": true
        },
        "profile": {
            "href": "http://localhost:8080/profile/user"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 2,
        "totalPages": 1,
        "number": 0
    }
}

6. delete access localhost:8080/user/1

Return status code:204

Visit GET again and visit localhost:8080/user, you will find that the number of users has been 1, indicating that the deletion has been successful

You can use postman test. In order not to map, just write as above, hope to understand

small function

In order to facilitate viewing and testing of the api, it can be integratedhal browser

You can add dependencies to the pom file

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>

Restart the project and visit: http://127.0.0.1:8080/browser/index.html#/, the effect is as shown in the figure

It's getting late, I wish everyone a happy April Fool's Day, I heard that someone is working overtime, I'm happy, if you like it, please follow

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324374594&siteId=291194637