Spring Boot 10 line build applications for RESTful

RESTful, now believed to have been no people do not know this stuff it! Concept of RESTful, I here do not introduce too much, the traditional Struts support for RESTful friendly enough, but SpringMVC for RESTful provide good support, commonly associated notes are:

@RestController
@GetMapping
@PutMapping
@PostMapping
@DeleteMapping
@ResponseBody
...

These annotations are RESTful and relevant in the mobile Internet, RESTful has been very widely used. RESTful concept put forward very early, but when no previous mobile Internet, most applications we do is the front and rear ends, regardless of the application of this architecture, the data are basically good front-end rendering back to the back end show, in which case there is no arena in basic RESTful Web applications, the rise of mobile Internet, let's set the background corresponding number of front-end items, so isolated front and rear end, RESTful successfully walked onto the stage.

Spring Boot inherited from Spring + SpringMVC, SpringMVC in full measure in Spring Boot in support for RESTful characteristics, while combined Jpa and automated provisioning, RESTful also provides for more support, allowing developers to write code that requires little (very less a few lines), you can quickly implement a RESTful style CRUD.

Next, Song Ge through a simple case, to show support for RESTful Spring Boot to everyone.

Real

Create Project

First create a Spring Boot engineering, introduction Web, Jpa, MySQL, Rest Repositoriesdependent on:

Once created, you need to lock the MySQL driver version and adding Druid database connection pool, complete dependence as follows:

<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>

Configuration database

Two main configuration, a database, and 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

Here configuration, and substantially uniform in Jpa.

Five basic information arranged in front of the database, including a database connection pool, database user name, password database, database, and connection address name database driver.

The next five lines equipped with the basic information of the JPA, respectively, generate SQL dialects, print out the generated SQL, every time you start the program select whether to update the table according to the actual situation, the database platform MySQL.

This two-stage configuration is configured on MySQL + JPA, and never used JPA small partners can refer to the previous article JPA Song Ge: http://www.javaboy.org/2019/0407/springboot-jpa.html

Construction of the entity class

@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;
    //省略 getter/setter
}
public interface BookRepository extends JpaRepository<Book,Long> {
}

Here is a configuration of an entity class Book, the other is equipped with a BookRepository, after a successful start of the project, the framework will be defined according to the Book class, automatically creates tables in the database, BookRepository the interface is inherited from JpaRepository, JpaRepository It comes with some basic CRUD method.

Well, the code is finished.

What? You seem to got nothing to write ah? Yes, I got nothing to write, and consequently do not write, a RESTful style CRUD application there, and this is the charm of Boot's Spring!

test

At this point, we can start the project to test the use POSTMAN to test (you can also choose their own tools conveniently HTTP requests).

At this point we have a number of projects have been the default interface, we look at each:

According to id Query Interface

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

This interface represents a book based on the id query:

Paging query

  • http://127.0.0.1:8080/books

This is a batch query interface, the default path is requested class name first letter lowercase, and add a suffix of s. This interface is actually a pagination query interface, it did not pass parameters to indicate the first page of the query, page 20 data.

Query results, in addition to the existing data, but also contains the paging data:

Paging data:

  1. size represents the number of records per query
  2. totalElements represents the total number of records
  3. totalPages represents the total number of pages
  4. number represents the current number of pages, starting from 0 count

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

Add to

也可以添加数据,添加是 POST 请求,数据通过 JSON 的形式传递,如下:

添加成功之后,默认会返回添加成功的数据。

修改

修改接口默认也是存在的,数据修改请求是一个 PUT 请求,修改的参数也是通过 JSON 的形式传递:

默认情况下,修改成功后,会返回修改成功的数据。

删除

当然也可以通过 DELETE 请求根据 id 删除数据:

删除成功后,是没有返回值的。

不需要几行代码,一个基本的增删改查就有了。

这些都是默认的配置,这些默认的配置实际上都是在 JpaRepository 的基础上实现的,实际项目中,我们还可以对这些功能进行定制。

查询定制

最广泛的定制,就是查询,因为增删改操作的变化不像查询这么丰富。对于查询的定制,非常容易,只需要提供相关的方法即可。例如根据作者查询书籍:

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

注意,方法的定义,参数要有 @Param 注解。

定制完成后,重启项目,此时就多了一个查询接口,开发者可以通过 http://localhost:8080/books/search 来查看和 book 相关的自定义接口都有哪些:

查询结果表示,只有一个自定义接口,接口名就是方法名,而且查询结果还给出了接口调用的示例。我们来尝试调用一下自己定义的查询接口:

开发者可以根据实际情况,在 BookRepository 中定义任意多个查询方法,查询方法的定义规则和 Jpa 中一模一样(不懂 Jpa 的小伙伴,可以参考干货|一文读懂 Spring Data Jpa!,或者在松哥个人网站 www.javaboy.org 上搜索 JPA,有相关教程参考)。但是,这样有一个缺陷,就是 Jpa 中方法名太长,因此,如果不想使用方法名作为接口名,则可以自定义接口名:

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

@RestResource 注解中,两个参数的含义:

  • rel 表示接口查询中,这个方法的 key
  • path 表示请求路径

这样定义完成后,表示接口名为 byauthor ,重启项目,继续查询接口:

除了 relpath 两个属性之外,@RestResource 中还有一个属性,exported 表示是否暴露接口,默认为 true ,表示暴露接口,即方法可以在前端调用,如果仅仅只是想定义一个方法,不需要在前端调用这个方法,可以设置 exported 属性为 false

如果不想暴露官方定义好的方法,例如根据 id 删除数据,只需要在自定义接口中重写该方法,然后在该方法上加 @RestResource 注解并且配置相关属性即可。

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);
}

另外生成的 JSON 字符串中的集合名和单个 item 的名字都是可以自定义的:

@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);
}

path 属性表示请求路径,请求路径默认是类名首字母小写+s,可以在这里自己重新定义。

其他配置

最后,也可以在 application.properties 中配置 REST 基本参数:

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

配置含义,从上往下,依次是:

  1. 给所有的接口添加统一的前缀
  2. 配置排序参数的 key ,默认是 sort
  3. 配置分页查询时页码的 key,默认是 page
  4. 配置分页查询时每页查询页数的 key,默认是size
  5. 配置每页最大查询记录数,默认是 20 条
  6. 分页查询时默认的页码
  7. 更新成功时是否返回更新记录
  8. 添加成功时是否返回添加记录

总结

本文主要向大家介绍了 Spring Boot 中快速实现一个 RESTful 风格的增删改查应用的方案,整体来说还是比较简单的,并不难。相关案例我已上传到 GitHub 上了,小伙伴可以自行下载:https://github.com/lenve/javaboy-code-samples

关于本文,有问题欢迎留言讨论。

关注公众号牧码小子,专注于 Spring Boot+微服务,定期视频教程分享,关注后回复 Java ,领取松哥为你精心准备的 Java 干货!

Guess you like

Origin www.cnblogs.com/lenve/p/10982998.html