博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Javaweb——Spring Boot 系列(12)使用 Data REST 读取数据
阅读量:3933 次
发布时间:2019-05-23

本文共 9948 字,大约阅读时间需要 33 分钟。

使用 Data REST 读取数据

一、Data REST

  • Spring Boot 与数据库交互,除了可以用 Spring Data JPA 的访问接口来获取数据的方式外,还可以使用 Spring Data REST 自动输出 REST 资源来获取数据,而且就代码量来说,后者的代码量更少。
  • Spring Data REST 目前支持将 Spring Data JPA,Spring Data MongoDB、Spring Data Neo4j、Spring Data GemFire 以及 Spring Data Cassandra 的 repository 自动转换成 REST 服务。
  • Spring Boot 不仅对 Data REST 支持,而且在 SpringBootRepositoryRestMvcConfiguration 类中为我们对 Data REST 的初始进行许多配置;因此,我们要使用 Data REST,只需在 POM 文件中添加相关依赖即可,RepositoryRestConfiguration 的配置则在 application.properties 中使用前缀 spring.data.rest 进行进行开启和关闭即可。

二、示例项目

  • 在这里我用一个简单项目对 Data REST 进行了测试,同时为了更方便的使用和访问 REST 服务,需要对浏览器安装相关插件。

1、浏览器 REST 支持

  • 要在浏览器中使用 REST 服务,就需要安装 REST client 插件,我使用的是谷歌浏览器,安装的插件叫 “Postman REST client”,如下图:
    在这里插入图片描述
  • 其他浏览器也应该有相关的插件。

2、新建项目与编辑依赖

  • 在 IDEA 中用项目新建引导,新建一个带初始的 Spring Boot 项目,初始依赖选择 JPA 和 Rest Repository。
  • 具体 POM 文件如下:
    4.0.0
    org.springframework.boot
    spring-boot-starter-parent
    1.3.0.M2
    com.pyc
    springbootrest
    0.0.1-SNAPSHOT
    springbootrest
    jar
    Demo project for Spring Boot
    1.8
    UTF-8
    org.springframework.boot
    spring-boot-starter-data-jpa
    org.springframework.boot
    spring-boot-starter-data-rest
    com.oracle
    ojdbc6
    11.2.0.2.0
    org.springframework.boot
    spring-boot-starter-test
    test
    org.junit.vintage
    junit-vintage-engine
    org.springframework.boot
    spring-boot-maven-plugin
  • 需要手动添加的就一个 ojdbc6.jar 的依赖。

3、数据源以及 Data REST 等配置

  • 打开 application.properties 文件,编辑数据源以及 Data REST 和其他一些相关配置,代码如下:
    spring.datasource.driverClassName=oracle.jdbc.OracleDriverspring.datasource.url=jdbc\:oracle\:thin\:@localhost\:1521\:xespring.datasource.username=bootspring.datasource.password=bootspring.jpa.hibernate.ddl-auto=updatespring.jpa.show-sql=truespring.jackson.serialization.indent_output=truedebug=truelogging.file=log.loglogging.level.org.springframework.web=DEBUG
  • 我之所以每个项目都生成一个 log 文件,主要是万一进行项目修改导致项目奔溃,我可以通过日志查看是因为增加了什么导致的奔溃。
  • 这里的配置,基本和上一篇项目的配置一样。

4、编辑实体类

  • 出于充分利用计算机资源的考虑,这里的实体类和上一篇的实体类的结构一样,也就是说载数据库中的目标数据表仍旧是 PERSON 这个数据表。
  • 代码如下:
    package com.pyc.springbootrest.domain;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic class Person {
    @Id @GeneratedValue private Long id; private String name; private Integer age; private String address; public Person() {
    super(); } public Person(Long id, String name, Integer age, String address) {
    super(); this.id = id; this.name = name; this.age = age; this.address = address; } public Long getId() {
    return id; } public void setId(Long id) {
    this.id = id; } public String getName() {
    return name; } public void setName(String name) {
    this.name = name; } public Integer getAge() {
    return age; } public void setAge(Integer age) {
    this.age = age; } public String getAddress() {
    return address; } public void setAddress(String address) {
    this.address = address; }}

5、为实体类配置 Repository

  • 这一步主要就是新建一个接口并继承 JpaRepository,用于 REST 服务获取数据用。
    package com.pyc.springbootrest.dao;import com.pyc.springbootrest.domain.Person;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.repository.query.Param;;import org.springframework.data.rest.core.annotation.RestResource;public interface PersonRepository extends JpaRepository
    {
    @RestResource(path = "nameStartsWith", rel = "nameStartsWith") Person findByNameStartsWith(@Param("name") String name);}
  • @RestResource 注解用于将该接口方法也暴露为 REST 资源。
  • 到这里无需再新建 Controller 什么的,直接运行项目。

6、浏览器测试 REST 服务

  • 打开谷歌浏览器,点击地址栏右边的 Postman REST client 图标打开插件,初始如下图:

    在这里插入图片描述

  • 在 Enter request URL here 输入框输入 localhost:8080/persons, 方法选择 GET,然后点击 SEND 按钮拉取数据,这个 URL 获取的数据就是 PERSON 表的所有数据,如下:

    在这里插入图片描述

  • 如果想获取单一对象,也就是数据表中的某一条记录,则可以用记录的 id 来获取,具体操作就是在上面的那个 URL 加上 /id 构成:localhost:8080/persons/id,例如获取 id 为 3 的,

    在这里插入图片描述

  • 使用刚刚的自定义接口方法查询,使用 URL:localhost:8080/persons/search/nameStartsWith?name=y,返回 JSON 格式数据内容如下:

    {
    "name": "yy", "age": 20, "address": "上海", "_links": {
    "self": {
    "href": "http://localhost:8080/persons/3" } }}
  • 测试分页查询,使用 url=localhost:8080/persons/?page=2&size=4,page=2 表示获取分页后的第二页,size=4 表示每页有四条记录,获得的数据如下:

    {
    "_links": {
    "first": {
    "href": "http://localhost:8080/persons?page=0&size=4" }, "prev": {
    "href": "http://localhost:8080/persons?page=1&size=4" }, "self": {
    "href": "http://localhost:8080/persons" }, "last": {
    "href": "http://localhost:8080/persons?page=2&size=4" }, "search": {
    "href": "http://localhost:8080/persons/search" }},"_embedded": {
    "persons": [ {
    "name": "csdn", "age": 20, "address": "杭州", "_links": {
    "self": {
    "href": "http://localhost:8080/persons/22" } } }, {
    "name": "lqy", "age": 21, "address": "dh", "_links": {
    "self": {
    "href": "http://localhost:8080/persons/41" } } }, {
    "name": "林秋延", "age": 21, "address": "东海", "_links": {
    "self": {
    "href": "http://localhost:8080/persons/42" } } }, {
    "name": "test", "age": 32, "address": "ds", "_links": {
    "self": {
    "href": "http://localhost:8080/persons/8" } } } ]},"page": {
    "size": 4, "totalElements": 12, "totalPages": 3, "number": 2 }}
  • 测试排序,使用 url=localhost:8080/persons/?sort=age,desc,以字段 age 为参考降序,如下图:

    在这里插入图片描述

  • 以上都是查询功能,接下来使用 POST 方法向数据库写入数据,使用 POST 方法为了让后台能够正确解析数据,需要先设置以下数据报头 Content-type 为 application/json ,URL 使用 localhost:8080/person

    在这里插入图片描述

  • 写入成功则会返回如下图:

    在这里插入图片描述

  • status 为 201 Created,离开浏览器,打开 Navicat 连接 Oracle 数据库查看目标数据表的情况如下:

    在这里插入图片描述

  • 成功将数据写入数据库。

  • 为了 REST 资源及时更新,使用 PUT 方法访问 localhost:8080/persons/43,当返回的 status 为 200 OK 就表示更新成功。

  • 再来测试从数据库从删除记录,删除记录的 url=localhost:8080/persons/id,例如删除 id 为 41 和 21 的记录

    在这里插入图片描述

  • 当返回的 status 如上图红色方框中那样,便是没有出错,此时回到 Navicat 刷新查看数据表,则发现 id 为 41 和 21 的记录已经删除:

    在这里插入图片描述

三、项目自定义设置

  • 除了使用 Spring Boot Data REST 提供的默认 URL 获取和提交数据外,还可以进行自定义。

1、根路径自定义

  • 先看看 SpringBootRepositoryRestMvcConfiguration 的源码:
    package org.springframework.boot.autoconfigure.data.rest;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.rest.core.config.RepositoryRestConfiguration;import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;@Configurationpublic class SpringBootRepositoryRestMvcConfiguration extends RepositoryRestMvcConfiguration {
    @Autowired( required = false ) private Jackson2ObjectMapperBuilder objectMapperBuilder; public SpringBootRepositoryRestMvcConfiguration() {
    } @Bean @ConfigurationProperties( prefix = "spring.data.rest" ) public RepositoryRestConfiguration config() {
    return super.config(); } protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {
    if (this.objectMapperBuilder != null) {
    this.objectMapperBuilder.configure(objectMapper); } }}
  • 从源码可以看出,对 Spring Data REST 的配置可以在 application.properties 文件中使用前缀 spring.data.rest 进行相关设置,这个在前文也说过了。
  • 根路径即 base-path,加上前缀如下:
    spring.data.rest.base-path=/api
  • 再 application.properties 文件中加上这句话后,此时项目的 REST 资源路径变成:localhost:8080/api/person

2、节点路径自定义

  • 根路径可以自定义,同样节点路径也支持自定义,不过自定义节点路径不是在 application.propertes 中操作,而是在实体类的 Repository 使用 @RepsoitoryRestResource 注解的 path 属性进行节点路径设置,示例如下:
    package com.pyc.springbootrest.dao;import com.pyc.springbootrest.domain.Person;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.repository.query.Param;;import org.springframework.data.rest.core.annotation.RepositoryRestResource;import org.springframework.data.rest.core.annotation.RestResource;@RepositoryRestResource(path = "people")public interface PersonRepository extends JpaRepository
    {
    @RestResource(path = "nameStartsWith", rel = "nameStartsWith") Person findByNameStartsWith(@Param("name") String name);}
  • 经过这一步操作,项目的 REST 资源的路径变成:localhost:8080/api/people

转载地址:http://zlqgn.baihongyu.com/

你可能感兴趣的文章
how to make jelly effect on belly in maya
查看>>
lesson3 some important things in CUDA
查看>>
lesson 4 communication pattern
查看>>
lesson 5 memory model
查看>>
lesson 6 threads synchronization
查看>>
lesson 7 strategies for efficient CUDA programming
查看>>
using cuda7.0 in matlab2015b with vs2013 compiler
查看>>
convert RGB image with hole into binary image with hole filled
查看>>
rotate object in matlab
查看>>
obj type using in findobj
查看>>
find border vertex
查看>>
matlab sliced variable
查看>>
set including path in mex
查看>>
create symbolic array
查看>>
TAUCS库的编译(vs2010)
查看>>
color vector using in plotting example points and lines between corresponding vertices
查看>>
laplacian,degree,adjacency and oriented incidence matrix, differential and laplacian coordinates
查看>>
mexcuda中矩阵数据的传输
查看>>
mexcuda输入nvcc中的参数
查看>>
mex 里面调用matlab函数
查看>>