RESTful, to now believe that no one does not know this thing! I won’t go into too much detail about the concept of RESTful here. Traditional Struts support for RESTful is not friendly, but SpringMVC provides good support for RESTful.

@RestController
@GetMapping
@PutMapping
@PostMapping
@DeleteMapping
@ResponseBody.Copy the code

These notes are all related to RESTful, which is widely used in the mobile web. The concept of RESTful was put forward long ago, but before the mobile Internet, most of the applications we made were separated from the front and back ends. In such applications, data is basically rendered at the back end and returned to the front end for display. At this time, RESTful is basically useless in Web applications. Let us have a set of background corresponding to multiple front-end projects, so the front and back end separation, RESTful smoothly onto the front stage.

Spring Boot inherits Spring + SpringMVC. All features supported by SpringMVC are accepted in Spring Boot. At the same time, combined with Jpa and automatic configuration, There is even more support for RESTful, allowing developers to quickly implement a RESTful style of add, delete, change and review with little to no code (a few lines).

Next, Songo uses a simple example to demonstrate Spring Boot’s RESTful support.

In actual combat

Create a project

First create a Spring Boot engineering, the introduction of the Web, Jpa, MySQL, Rest Repositories depends on:

Add the Druid database connection pool to the Druid database and lock the MySQL driver version.

<dependencies>
    <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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
        <version>5.1.27</version>
    </dependency>
</dependencies>
Copy the code

Configuring the Database

There are two main configurations, one is database, the other is Jpa:

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql:///test01
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=mysql
spring.jpa.database=mysql
Copy the code

The configuration here is basically the same as in Jpa.

The first five lines configure basic database information, including database connection pool, database user name, database password, database connection address, and database driver name.

The next five lines are configured with the basic information of JPA, which respectively represent the dialect to generate SQL, print the generated SQL, choose whether to update the table according to the actual situation when starting the project, and the database platform is MySQL.

These two configuration is about MySQL + JPA configuration, used JPA friend can refer to loose before JPA article: www.javaboy.org/2019/0407/s…

Building entity Classes

@Entity(name = "t_book")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "book_name")
    private String name;
    private String author;
    / / omit getter/setter
}
public interface BookRepository extends JpaRepository<Book.Long> {}Copy the code

In this case, a new entity class Book is configured, and a new BookRepository is configured. After the project is successfully started, the framework will automatically create the corresponding tables in the database according to the definition of the Book class. The BookRepository interface is inherited from JpaRepository, which comes with some basic add, delete, alter, and query methods.

Okay, that’s the code.

What? I don’t think you wrote anything, do you? Yes, nothing to write, nothing to write, a RESTful style of add, delete, change and check applications have, this is the charm of Spring Boot!

test

At this point, we’re ready to launch the project and test it, using POSTMAN (or the HTTP request tool of your choice).

Now that our project has some interfaces by default, let’s look at them separately:

Query interfaces by ID

  • http://127.0.0.1:8080/books/ {id}

This interface is used to query a book by id:

Paging query

  • http://127.0.0.1:8080/books

This is a batch query interface. The default request path is lowercase with an S suffix. This interface is actually a paging query interface, no parameters, indicating the query first page, 20 data per page.

The query result contains pagination data in addition to the expected data:

In paging data:

  1. Size indicates the number of query records per page
  2. TotalElements indicates the total number of records
  3. TotalPages indicates the total number of pages
  4. Number indicates the current page count, starting from 0

If you want to page or sort queries, you can use links in _links. http://127.0.0.1:8080/books?page=1&size=3&sort=id, desc.

add

You can also add data, which is a POST request, and the data is passed in JSON as follows:

After the data is added successfully, the data is returned by default.

Modify the

The modify interface also exists by default, the data modify request is a PUT request, and the modified parameters are also passed in JSON form:

By default, the modified data is returned after the modification is successful.

delete

It is also possible to DELETE data by ID with a DELETE request:

No value is returned after a successful deletion.

You don’t need a few lines of code, a basic add, delete, change and check.

These are default configurations that are actually implemented on the basis of JpaRepository and can be customized in real projects.

Query the custom

The most extensive customization is for queries, because add, delete and change operations are not as varied as queries. It is easy to customize queries by providing relevant methods. For example, query a book by author:

public interface BookRepository extends JpaRepository<Book.Long> {
    List<Book> findBookByAuthorContaining(@Param("author") String author);
}
Copy the code

Notice that methods are defined with @param annotations.

Custom completed, restart the project, this time is a query interface, the developers can use http://localhost:8080/books/search to view and book related custom interfaces are:

The result of the query shows that there is only one custom interface, the name of which is the name of the method, and the result gives an example of interface invocation. Let’s try calling our own query interface:

Developers can according to the actual situation, defined in BookRepository any number of query methods, exactly as in the definition of the rules and Jpa query method (don’t understand the Jpa friend, you can refer to dry | article read Spring Data Jpa! Or search for JPA on Songo’s website www.javaboy.org for tutorials). If you don’t want to use the method name as the interface name, you can customize the interface name:

public interface BookRepository extends JpaRepository<Book.Long> {
    @RestResource(rel = "byauthor",path = "byauthor")
    List<Book> findBookByAuthorContaining(@Param("author") String author);
}
Copy the code

In the @restResource annotation, the meanings of the two parameters are:

  • Rel represents the key of this method in the interface query
  • Path Indicates the request path

After defining the interface as byAuthor, restart the project and continue to query the interface:

If you want to define a method, you don’t need to call the method in the front end. If you want to define a method, you don’t need to call the method in the front end. You can set the exported property to false.

If you don’t want to expose an officially defined method, such as deleting data by ID, simply override the method in your custom interface, annotate it with @RestResource and configure the properties.

public interface BookRepository extends JpaRepository<Book.Long> {
    @RestResource(rel = "byauthor",path = "byauthor")
    List<Book> findBookByAuthorContaining(@Param("author") String author);
    @Override
    @RestResource(exported = false)
    void deleteById(Long aLong);
}
Copy the code

In addition, the collection names and individual item names in the generated JSON string are customizable:

@RepositoryRestResource(collectionResourceRel = "bs",itemResourceRel = "b",path = "bs")
public interface BookRepository extends JpaRepository<Book.Long> {
    @RestResource(rel = "byauthor",path = "byauthor")
    List<Book> findBookByAuthorContaining(@Param("author") String author);
    @Override
    @RestResource(exported = false)
    void deleteById(Long aLong);
}
Copy the code

The path property represents the request path, which by default is lowercase + S and can be redefined here.

Other configuration

Finally, REST basic parameters can also be configured in application.properties:

spring.data.rest.base-path=/api
spring.data.rest.sort-param-name=sort
spring.data.rest.page-param-name=page
spring.data.rest.limit-param-name=size
spring.data.rest.max-page-size=20
spring.data.rest.default-page-size=0
spring.data.rest.return-body-on-update=true
spring.data.rest.return-body-on-create=true
Copy the code

The configuration meanings are as follows from top to bottom:

  1. Add a uniform prefix to all interfaces
  2. Configures the key of the sort parameter. The default is sort
  3. Configure the key of the page number for paging query. The default is page
  4. This parameter specifies the key for paging query. The default key is size
  5. Set the maximum number of query records on a page. The default value is 20
  6. Default page number for paging queries
  7. Whether to return the update record when the update is successful
  8. Whether to return the add record if the add is successful

conclusion

This article mainly introduces the Spring Boot to quickly implement a RESTful style of add, delete, change and check application scheme, overall is relatively simple, not difficult. Related cases I have uploaded to GitHub, partners can download: github.com/lenve/javab… .

If you have any questions about this article, please leave a comment.

Pay attention to the public account [Jiangnan little Rain], focus on Spring Boot+ micro service and front and back end separation and other full stack technology, regular video tutorial sharing, after attention to reply to Java, get Songko for you carefully prepared Java dry goods!