1 introduction

Visit pumpkin Talk www.pkslow.com for more exciting articles!

Springboot + Spring MVC greatly simplifies RESTful development of Web applications, while Spring Data REST is simpler. Spring Data REST is built on top of Data Repository, which exposes Resository as a Web service in HATEOAS style without the need to write the Controller layer by hand.

HATEOAS, or Hypermedia as the Engine of Application State, is a more mature REST model that includes link information in the representation of resources, from which clients can discover executable actions.

Spring Data REST supports Spring Data JPA, Spring Data MongoDB, Spring Data Neo4j, Spring Data GenFire, Spring Data Cassandra, Here we choose the familiar JPA.

2 Take an example

Let’s use an example to get a feel for it.

2.1 Creating a Project

We used Spring Initializr to quickly create a Springboot project. The selected dependent components are as follows:

  • (1)Spring Web: provideWebService;
  • (2)Rest Repositories: provideSpring Data RESTSupport;
  • (3)Spring Data JPAThrough:JPAprovideRepositoryMode of data access;
  • (4)H2 Database:H2Database, which is used for simplicity.

After the import, the following dependencies exist in pom. XML:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>runtime</scope>
</dependency>
Copy the code

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
}
Copy the code

2.3 Repository interface definition

Define the Repository interface for manipulating databases, as shown below:

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> {}Copy the code

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

2.4 Enabling Access

Start the Springboot application directly, and set port to 8080.

Let’s do a basic operation with Postman.

Feature:

Query:

Query by primary key ID:

Modification:

Delete:

As you can see, the Json returned has links, which is the HATEOAS style.

3 More exploration

3.1 Paging and sorting functions

To quickly implement paging and sorting, you just need to change the father of the Repository interface to PagingAndSortingRepository, as shown below:

@RepositoryRestResource(path = "user")
public interface UserRepository extends PagingAndSortingRepository<User.Integer> {}Copy the code

FindAll (Sort var1); findAll(Pageable var1);

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

    Page<T> findAll(Pageable var1);
}
Copy the code

Query http://localhost:8080/user? Page =1&size=2&sort= ID,desc, indicates that the second page is queried. Two records are displayed on each page in reverse order. 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}}Copy the code

You can see that the page starts at 0, with 1 indicating the second page. The results also provide links to the first page, previous page, current page, next page and last page; And paging information.

3.2 Event Listening

REST provides eight Repository-based 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); }}Copy the code

After adding, modifying, and deleting, the following logs are generated:

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]'}
Copy the code

After an event is successfully executed, you can use this function to implement a lot of service logic, such as recording operation logs and deleting other related data.

3.3 the path

The default base path is /, which can be configured via spring.data.rest.base-path= API, which becomes localhost:8080/ API /user.

4 Integrated HAL Browser view

HAL Browser is a dedicated front-end tool for browsing JSON based Hypertext Application Language. We have already provided RESTful services in the style of HATEOAS, HAL Browser can be easily viewed.

Add dependencies:

<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-rest-hal-browser</artifactId>
  <version>3.3.2 rainfall distribution on 10-12. RELEASE</version>
</dependency>
Copy the code

Starts to http://localhost:8080/browser/index.html#/ is as follows:

CRUD operations can be performed, which will not be shown in detail.

5 concludes

This article introduces Spring Data REST, which can facilitate RESTful service development. However, it is understood that the project does not use many, simple learning, without loss, is a way to understand the concept of Spring buckets and architecture.

The code for this article can be accessed at SpringDataRest.


Welcome to pay attention to the wechat public number “Pumpkin slow Talk”, will continue to update for you…

Read more and share more; Write more. Organize more.