Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Simplify RESTful development and Spring Data REST reduces your workload


Jun 01, 2021 Article blog


Table of contents


1. Introduction

Springboot and Spring MVC simplify RESTful development in web applications, but one simpler one is Spring Spring Data REST Spring Data REST is built on Data Repository which resository directly to Web services in HATEOAS style without having to write the Controller layer.

  • HATEOAS or Hypermedia as the Engine of Application State is a more mature REST model that includes link information in the expression of resources, and clients can discover executable actions based on links.

Spring Data REST Spring Data JPA Spring Data MongoDB Spring Data Neo4j Spring Data GenFire Spring Data Cassandra and choose the more familiar JPA here.

2 For example

Let's take an example and feel it.

2.1 Create a project

We quickly created the Springboot project with Spring Spring Initializr The selected dependent components are as follows:

 Simplify RESTful development and Spring Data REST reduces your workload1

  • (1) Spring Web: Providing Web Services;
  • (2) Rest Repositories: Support for Spring Data REST
  • (3) Spring Data JPA: Repository data access through JPA
  • (4) H2 Database:H2 database, in order to facilitate the simplicity of use of the database.

(Recommended course: Spring tutorial)

The corresponding pom.xml after import depends on the following:

lt; d ependency& lt; g roupId&org.springframework.boot</groupId& lt; a rtifactId&spring-boot-starter-web</artifactId& lt;/dependency& lt; d ependency& lt; g roupId&org.springframework.boot</groupId& lt; a rtifactId&spring-boot-starter-data-jpa</artifactId& lt;/dependency& lt; d ependency& lt; g roupId&org.springframework.boot</groupId& lt; a rtifactId&spring-boot-starter-data-rest</artifactId& lt;/dependency& lt; d ependency& lt; g roupId&com.h2database</groupId& lt; a rtifactId&h2</artifactId& lt; scope&runtime</scope& lt;/dependency&

2.2 Entity class

Create an entity class, User, as follows:

package com.pkslow.rest.entity;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;


@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    private Integer age;
    private String email;

  
  //getter & setter
}

2.3 Repository interface definition

Define Repository interface for operating the database, as follows:

package com.pkslow.rest.repo;


import com.pkslow.rest.entity.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;


@RepositoryRestResource(path = "user")
public interface UserRepository extends CrudRepository<User, Integer> {
}

Note RepositoryRestResource is Data REST used to expose Repository path is the access path, is set to user and the access address is http://localhost:8080/user

2.4 Start the access

With the above code ready, just launch the Springboot app, and we set the port to 8080, with access as follows:

 Simplify RESTful development and Spring Data REST reduces your workload2

Let's do a basic operation with Postman

New:

 Simplify RESTful development and Spring Data REST reduces your workload3

Inquire:

 Simplify RESTful development and Spring Data REST reduces your workload4

Query by primary key ID:

 Simplify RESTful development and Spring Data REST reduces your workload5

revise:

 Simplify RESTful development and Spring Data REST reduces your workload6

Delete:

 Simplify RESTful development and Spring Data REST reduces your workload7

It's not hard to see that the Json are linked, and that's HATEOAS style.

3 More explorations

3.1 Paging and sorting

Paging and sorting can be implemented quickly by simply changing Repository parent interface to PagingAndSortingRepository

@RepositoryRestResource(path = "user") public interface UserRepository extends PagingAndSortingRepository<User, Integer> { }

There are actually two more findAll(Sort var1) and findAll(Pageable var1) as follows:

public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> { Iterable<T> findAll(Sort var1);


    Page<T> findAll(Pageable var1);
}

Query http: // localhost: 8080 / user? Page = 1 & size = 2 & sort = ID, DESC, indicating the second page of the query, 2 records per page, displayed in an ID. as follows:

{ "_embedded": { "users": [ { "name": "pkslow.com", "age": 18, "email": "[email protected]", "_links": { "self": { "href": " http://localhost:8080/user/33 " }, "user": { "href": " http://localhost:8080/user/33 " } } }, { "name": "pkslow.com", "age": 18, "email": "[email protected]", "_links": { "self": { "href": " http://localhost:8080/user/32 " }, "user": { "href": " http://localhost:8080/user/32 " } } } ] }, "_links": { "first": { "href": " http://localhost:8080/user?page=0&size=2&sort=id,desc " }, "prev": { "href": " http://localhost:8080/user?page=0&size=2&sort=id,desc " }, "self": { "href": " http://localhost:8080/user?page=1&size=2&sort=id,desc " }, "next": { "href": " http://localhost:8080/user?page=2&size=2&sort=id,desc " }, "last": { "href": " http://localhost:8080/user?page=17&size=2&sort=id,desc " }, "profile" : { "href": " http://localhost:8080/profile/user " } }, "page": { "size": 2, "totalElements": 35, "totalPages": 18, "number": 1 } }

You can find that page starts at 0, 1 represents the second page, and the return results provide links to the first, previous, current, next, and last pages, as well as paginated information.

(Recommended micro-class: Spring micro-class.) )

3.2 Event monitoring

REST provides eight Repository events, as follows:

  • BeforeCreateEvent
  • AfterCreateEvent
  • BeforeSaveEvent
  • AfterSaveEvent
  • BeforeLinkSaveEvent
  • AfterLinkSaveEvent
  • BeforeDeleteEvent
  • AfterDeleteEvent

Add a custom event as follows:

package com.pkslow.rest.event;


import com.pkslow.rest.entity.User;
import org.springframework.data.rest.core.event.AbstractRepositoryEventListener;
import org.springframework.stereotype.Component;


@Component
public class PkslowEventListener extends AbstractRepositoryEventListener<User> {


    @Override
    public void onBeforeCreate(User entity) {
        System.out.println("pkslow creating:" + entity);
    }


    @Override
    public void onBeforeSave(User entity) {
        System.out.println("pkslow saving:" + entity);
    }


    @Override
    public void onAfterDelete(User entity) {
        System.out.println("pkslow deleted:" + entity);
    }
}

After adding, modifying, and deleting, the logs are as follows:

pkslow creating:User{id=null, name='pkslow.com', age=18, email='[email protected]'} pkslow saving:User{id=32, name='pkslow.com', age=20, email='[email protected]'} pkslow deleted:User{id=14, name='pkslow.com', age=18, email='[email protected]'}

Explaining the successful execution of the event, combined with this capability, enables many business logics, such as logging operations after deletion and deleting other related data.

(Recommended tutorial: Spring Boot those things.) )

3.3 Path

The default underlying path is / , which can be configured by spring.data.rest.base-path=api which localhost:8080/api/user

4 Integrated HAL Browser view

HAL Browser is a front-end tool dedicated to browsing JSON Hypertext Application Language We've already provided HATEOAS RESTful service that HAL Browser can easily view.

Join dependencies:

lt; d ependency& lt; g roupId&org.springframework.data</groupId& lt; a rtifactId&spring-data-rest-hal-browser</artifactId& lt; version&3.3.2.RELEASE</version& lt;/dependency&

The http://localhost:8080/browser/index.html#/ of post-start access are as follows:

 Simplify RESTful development and Spring Data REST reduces your workload8

CRUD operations can be performed, as shown.

The above is about Spring Data REST introduction, it can be convenient for everyone to use RESTful development, I hope to help you, although the project is not a great opportunity to use, but also can expand some knowledge.