SpringBoot之Spring Data REST

来源:互联网 发布:河北11选五任6遗漏数据 编辑:程序博客网 时间:2024/05/18 02:27

一、起源
RESTful架构,就是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。但是,到底什么是RESTful架构,并不是一个容易说清楚的问题。下面,我就谈谈我理解的RESTful架构。

REST这个词,是Roy Thomas Fielding在他2000年的博士论文中提出的。

REST的名称”表现层状态转化”中,省略了主语。”表现层”其实指的是”资源”(Resources)的”表现层”。
所谓”资源”,就是网络上的一个实体,或者说是网络上的一个具体信息。它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的实在。你可以用一个URI(统一资源定位符)指向它,每种资源对应一个特定的URI。要获取这个资源,访问它的URI就可以,因此URI就成了每一个资源的地址或独一无二的识别符。所谓”上网”,就是与互联网上一系列的”资源”互动,调用它的URI。

总结一下什么是RESTful架构:

  1. 每一个URI代表一种资源;
  2. 客户端和服务器之间,传递这种资源的某种表现层;
  3. 客户端通过四个HTTP动词,对服务器端资源进行操作,实现”表现层状态转化”。

二、Spring Data REST
Spring Data JPA是基于Spring Data的repository之上,可以将repository自动输出为REST资源。目前Spring Data REST支持将Spring Data JPA、Spring DataMongoDB、Spring Data Neo4j、Spring Data GemFire以及Spring Data Cassandra的repository自动转换成REST服务。
配置方式:
1.继承方式:

@Configurationpublic class MyRepositoryRestMvcConfiguration extends RepositoryRestMvcConfiguration {@Overridepublic RepositoryRestConfiguration config() {return super.config();}//其他可重写以config开头的方法}

2.导入方式:

@Configuration@Import(RepositoryRestMvcConfiguration.class)public class AppConfig {}

三、Springboot的支持
Spring Boot对Spring Data REST的自动配置放置在Rest中:
这里写图片描述

通过SpringBootRepositoryRestMvcConfiguration类的源码我们可以得出,Spring Boot已经为我们自动配置了RepositoryRestConfiguration,所以在Spring Boot中使用Spring Data REST只需引入spring-boot-starter-data-rest的依赖,无须任何配置即可使用。
Spring Boot通过在application.properties中配置以“spring.data.rest”为前缀的属性来配置RepositoryRestConfiguration:

# DATA REST (RepositoryRestProperties)spring.data.rest.base-path= # Base path to be used by Spring Data REST to expose repository resources.spring.data.rest.default-page-size= # Default size of pages.spring.data.rest.detection-strategy=default # Strategy to use to determine which repositories get exposed.spring.data.rest.enable-enum-translation= # Enable enum value translation via the Spring Data REST default resource bundle.spring.data.rest.limit-param-name= # Name of the URL query string parameter that indicates how many results to return at once.spring.data.rest.max-page-size= # Maximum size of pages.spring.data.rest.page-param-name= # Name of the URL query string parameter that indicates what page to return.spring.data.rest.return-body-on-create= # Return a response body after creating an entity.spring.data.rest.return-body-on-update= # Return a response body after updating an entity.spring.data.rest.sort-param-name= # Name of the URL query string parameter that indicates what direction to sort results.

四、实例,(和在Spring Boot中使用和在Spring MVC中使用Spring Data REST是一样的)
1.pom.xml: 这里用mysql数据库

    <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>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <scope>runtime</scope>    </dependency>

2.实体类Worker.java

@Entitypublic class Worker {    @Id    @GeneratedValue    private Long id;    private String name;    private Integer age;    private String address;    public Worker() {        super();    }    public Worker(Long id, String name, Integer age, String address) {        super();        this.id = id;        this.name = name;        this.age = age;        this.address = address;    }    //省略set、get.....}

3.实体类的Repository,WorkerRepository.java

public interface WorkerRepository extends JpaRepository<Worker, Long> {    Worker findByNameStartsWith(String name);}

五、测试(测试工具为[Postman,安装及介绍地址])

1.sql,项目启动后会自动建表:

INSERT INTO `test`.`worker` (`id`, `address`, `age`, `name`) VALUES ('1', '云南', '20', '张三');INSERT INTO `test`.`worker` (`id`, `address`, `age`, `name`) VALUES ('2', '桂林', '21', '李四');INSERT INTO `test`.`worker` (`id`, `address`, `age`, `name`) VALUES ('3', '广西', '22', '王五');INSERT INTO `test`.`worker` (`id`, `address`, `age`, `name`) VALUES ('4', '柳州', '23', '赵六');INSERT INTO `test`.`worker` (`id`, `address`, `age`, `name`) VALUES ('5', '贵州', '24', '扯七');INSERT INTO `test`.`worker` (`id`, `address`, `age`, `name`) VALUES ('6', '贵阳', '25', '拉八');

节点路径为http://localhost:5000/workers,这是Spring Data REST的默认规则,就是在实体类之后加“s”来形成路径。
2.列表(http://localhost:5000/workers)
这里写图片描述

3.获取单一对象(http://localhost:5000/workers/1)
这里写图片描述

4.查询(http://localhost:5000/workers/search/nameStartsWith?name=王)
在上面的自定义实体类Repository中定义了findByNameStartsWith方法,若想此方法也暴露为REST资源,需做如下修改:

public interface WorkerRepository extends JpaRepository<Worker, Long> {    @RestResource(path = "nameStartsWith", rel = "nameStartsWith")    Worker findByNameStartsWith(@Param("name") String name);}

这里写图片描述

5.分页(http://localhost:5000/workers?page=1&size=2)
这里写图片描述

6.排序(http://localhost:5000/workers?sort=age,desc),按年龄倒叙
这里写图片描述

7.保存
向http://localhost:5000/workers发起POST请求,将我们要保存的数据放置在请求体中,数据类型设置为JSON:
这里写图片描述

8.更新
现在我们更新新增的id为2的数据,用PUT方式访问http://localhost:5000/workers/2,并修改提交的数
据:
这里写图片描述

9.删除
我们删除刚才新增的id为2的数据,使用DELETE方式访问http://localhost:5000/workers/2。
这里写图片描述
再查询全量:
这里写图片描述

六、拓展
1.定制根路径:
在上面的实战例子中,我们访问的REST资源的路径是在根目录下的,即http://localhost:5000/workers/,如果我们需要定制根路径的话,只需在Spring Boot的application.yml下增加如下定义即可:

server:  port: 5000spring:  datasource:    driver-class-name: com.mysql.jdbc.Driver    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8    username: root    password: password  jpa:    hibernate:      ddl-auto: update  # 第一次简表create  后面用update    show-sql: true  data:    rest:      base-path: /api

此时REST资源的路径变成了http://localhost:5000/api/workers

2.定制节点路径
上例实战中,我们的节点路径为http://localhost:5000/api/workers,这是Spring Data REST的默认规则,就是在实体类之后加“s”来形成路径。我们知道worker的复数是workers,在类似的情况下要对映射的名称进行修改的话,我们需要在实体类Repository上使用@RepositoryRestResource注解的path属性进行修改,代码如下:

@RepositoryRestResource(path = "work")public interface WorkerRepository extends JpaRepository<Worker, Long> {    @RestResource(path = "nameStartsWith", rel = "nameStartsWith")    Worker findByNameStartsWith(@Param("name") String name);}

此时我们访问REST服务的地址变为:http://localhost:5000/api/work
这里写图片描述

参考资料《JavaEE开发的颠覆者 Spring Boot》

新手一枚,欢迎拍砖~ ~ ~

原创粉丝点击