1. 什么是Spring Data REST

  Spring Data JPA是基于Spring Data 的Repository之上,可以将Repository自动输出为REST资源。目前Spring Data REST支持将Spring Data JPA、Spring Data MongoDB、Spring Data Neo4j、Spring Data Gemfire以及Spring Data Cassandra的Repository自动转换成REST服务。

  2. Spring mvc中配置使用Spring Data REST

  Spring Data REST的配置是定义在RepositoryRestMvcConfiguration配置类中已经配置好了,我们可以通过继承此类或者直接在自己的配置类上@Import此配置类

  3. Spring boot的支持  

  Spring Boot对Spring Data REST的自动配置放置在rest包中

通过SpringBootRestConfiguration类的源码我们可以得出,Spring Boot已经为我们自动配置了RepositoryRestConfiguration,所以在Spring boot中使用Spring Data REST只需引入spring-boot-starter-data-rest的依赖,无须任何配置即可使用。

Spring boot通过在application.properties中配置以“spring.data.rest”为前缀的属性来配置RepositoryRestConfiguration

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; @Order(0)
class SpringBootRepositoryRestConfigurer extends RepositoryRestConfigurerAdapter { @Autowired(required = false)
private Jackson2ObjectMapperBuilder objectMapperBuilder; @Autowired
private RepositoryRestProperties properties; @Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
this.properties.applyTo(config);
} @Override
public void configureJacksonObjectMapper(ObjectMapper objectMapper) {
if (this.objectMapperBuilder != null) {
this.objectMapperBuilder.configure(objectMapper);
}
} }
 @ConfigurationProperties(prefix = "spring.data.rest")
public class RepositoryRestProperties { /**
* Base path to be used by Spring Data REST to expose repository resources.
*/
private String basePath; /**
* Default size of pages.
*/
private Integer defaultPageSize; /**
* Maximum size of pages.
*/
private Integer maxPageSize; /**
* Name of the URL query string parameter that indicates what page to return.
*/
private String pageParamName; /**
* Name of the URL query string parameter that indicates how many results to return at
* once.
*/
private String limitParamName; /**
* Name of the URL query string parameter that indicates what direction to sort
* results.
*/
private String sortParamName; /**
* Strategy to use to determine which repositories get exposed.
*/
private RepositoryDetectionStrategies detectionStrategy = RepositoryDetectionStrategies.DEFAULT; /**
* Content type to use as a default when none is specified.
*/
private MediaType defaultMediaType; /**
* Return a response body after creating an entity.
*/
private Boolean returnBodyOnCreate; /**
* Return a response body after updating an entity.
*/
private Boolean returnBodyOnUpdate; /**
* Enable enum value translation via the Spring Data REST default resource bundle.
* Will use the fully qualified enum name as key.
*/
private Boolean enableEnumTranslation; public String getBasePath() {
return this.basePath;
} public void setBasePath(String basePath) {
this.basePath = basePath;
} public Integer getDefaultPageSize() {
return this.defaultPageSize;
} public void setDefaultPageSize(Integer defaultPageSize) {
this.defaultPageSize = defaultPageSize;
} public Integer getMaxPageSize() {
return this.maxPageSize;
} public void setMaxPageSize(Integer maxPageSize) {
this.maxPageSize = maxPageSize;
} public String getPageParamName() {
return this.pageParamName;
} public void setPageParamName(String pageParamName) {
this.pageParamName = pageParamName;
} public String getLimitParamName() {
return this.limitParamName;
} public void setLimitParamName(String limitParamName) {
this.limitParamName = limitParamName;
} public String getSortParamName() {
return this.sortParamName;
} public void setSortParamName(String sortParamName) {
this.sortParamName = sortParamName;
} public RepositoryDetectionStrategies getDetectionStrategy() {
return this.detectionStrategy;
} public void setDetectionStrategy(RepositoryDetectionStrategies detectionStrategy) {
this.detectionStrategy = detectionStrategy;
} public MediaType getDefaultMediaType() {
return this.defaultMediaType;
} public void setDefaultMediaType(MediaType defaultMediaType) {
this.defaultMediaType = defaultMediaType;
} public Boolean getReturnBodyOnCreate() {
return this.returnBodyOnCreate;
} public void setReturnBodyOnCreate(Boolean returnBodyOnCreate) {
this.returnBodyOnCreate = returnBodyOnCreate;
} public Boolean getReturnBodyOnUpdate() {
return this.returnBodyOnUpdate;
} public void setReturnBodyOnUpdate(Boolean returnBodyOnUpdate) {
this.returnBodyOnUpdate = returnBodyOnUpdate;
} public Boolean getEnableEnumTranslation() {
return this.enableEnumTranslation;
} public void setEnableEnumTranslation(Boolean enableEnumTranslation) {
this.enableEnumTranslation = enableEnumTranslation;
} public void applyTo(RepositoryRestConfiguration configuration) {
if (this.basePath != null) {
configuration.setBasePath(this.basePath);
}
if (this.defaultPageSize != null) {
configuration.setDefaultPageSize(this.defaultPageSize);
}
if (this.maxPageSize != null) {
configuration.setMaxPageSize(this.maxPageSize);
}
if (this.pageParamName != null) {
configuration.setPageParamName(this.pageParamName);
}
if (this.limitParamName != null) {
configuration.setLimitParamName(this.limitParamName);
}
if (this.sortParamName != null) {
configuration.setSortParamName(this.sortParamName);
}
if (this.detectionStrategy != null) {
configuration.setRepositoryDetectionStrategy(this.detectionStrategy);
}
if (this.defaultMediaType != null) {
configuration.setDefaultMediaType(this.defaultMediaType);
}
if (this.returnBodyOnCreate != null) {
configuration.setReturnBodyOnCreate(this.returnBodyOnCreate);
}
if (this.returnBodyOnUpdate != null) {
configuration.setReturnBodyOnUpdate(this.returnBodyOnUpdate);
}
if (this.enableEnumTranslation != null) {
configuration.setEnableEnumTranslation(this.enableEnumTranslation);
}
} }

实战演练

1.定义实体类

2.定义Repository

3.测试

 @Entity
public 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;
} }
public interface PersonRepository extends JpaRepository<Person, Long> {

    Person findByNameStartsWith(@Param("name")String name);
}

GET请求

  http://localhost:8080/psersons    获取列表

  http://localhost:8080/1        获取id为1的对象

  在上面的自定义Repository中定义了findByNameStartsWith方法,若想此方法也暴露为REST资源,需做如下修改

public interface PersonRepository extends JpaRepository<Person, Long> {

    @RestResource(path = "nameStartsWith", rel = "nameStartsWith")
Person findByNameStartsWith(@Param("name")String name);
}

此时使用GET访问http://localhost:8080/persons/search/nameStartsWith?name=kevin,可实现查询操作

  http://localhost:8080/persons/?page=1&size=2    分页查询,page-1即第2页,size=2即每页数量为2

  http://localhost:8080/persons/?sort=age,desc      排序,即按照age属性倒序

POST请求

  http://localhost:8080/persons ,并将数据放到请求体中      保存

  http://localhost:8080/persons/21,并将数据放到请求体中      更新

DELETE请求

  http://localhost:8080/persons/21                  删除

4. 定制

  (1)定制根路径

  在上面的实战例子中,我们访问的REST资源的路径是在根目录下的,即http://localhost:8080/persos,如果我们需要定制根路径的话,只需要在Spring Boot的application.properties中添加定义 spring.data.rest.base-path= /api 此时REST资源的路径变成了http://localhost:8080/api/persons

  (2)定制节点路径

  上例实战中,我们的节点路径为http://localhost:8080/persons,这是Spring Data REST的默认规则,就是在实体类之后加“s”来形成路径。如果要对映射的名称进行修改的话,需要在实体类Repository上使用@RepositoryRestResource注解的path属性进行修改

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

此时访问REST服务的地址变成http://localhost:8080/api/people

 

初入spring boot(八 )Spring Data REST的更多相关文章

  1. Spring Boot(八):RabbitMQ详解

    Spring Boot(八):RabbitMQ详解 RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用. 消息中间件在互联网公司的使用中越来越多 ...

  2. Spring Boot集成Spring Data Reids和Spring Session实现Session共享

    首先,需要先集成Redis的支持,参考:http://www.cnblogs.com/EasonJim/p/7805665.html Spring Boot集成Spring Data Redis+Sp ...

  3. Spring Boot 结合Spring Data结合小项目(增,删,查,模糊查询,分页,排序)

    本次做的小项目是类似于,公司发布招聘信息,因此有俩个表,一个公司表,一个招聘信息表,俩个表是一对多的关系 项目整体结构: Spring Boot和Spring Data结合的资源文件 applicat ...

  4. spring boot系列(五)spring boot 配置spring data jpa (查询方法)

    接着上面spring boot系列(四)spring boot 配置spring data jpa 保存修改方法继续做查询的测试: 1 创建UserInfo实体类,代码和https://www.cnb ...

  5. Spring Boot 整合Spring Data JPA

    Spring Boot整合Spring Data JPA 1)加入依赖 <dependency> <groupId>org.springframework.boot</g ...

  6. Spring Boot中Spring data注解的使用

    文章目录 Spring Data Annotations @Transactional @NoRepositoryBean @Param @Id @Transient @CreatedBy, @Las ...

  7. Spring Boot 之Spring data JPA简介

    文章目录 添加依赖 添加entity bean 创建 Dao Spring Data Configuration 测试 Spring Boot 之Spring data JPA简介 JPA的全称是Ja ...

  8. 一:Spring Boot、Spring Cloud

    上次写了一篇文章叫Spring Cloud在国内中小型公司能用起来吗?介绍了Spring Cloud是否能在中小公司使用起来,这篇文章是它的姊妹篇.其实我们在这条路上已经走了一年多,从16年初到现在. ...

  9. 基于Spring Boot、Spring Cloud、Docker的微服务系统架构实践

    由于最近公司业务需要,需要搭建基于Spring Cloud的微服务系统.遍访各大搜索引擎,发现国内资料少之又少,也难怪,国内Dubbo正统治着天下.但是,一个技术总有它的瓶颈,Dubbo也有它捉襟见肘 ...

  10. spring boot 与 spring cloud 关系

    公司使用spring cloud,所以稍微了解一下 看了一下spring官网对 spring boot 以及 spring cloud 的解释 Spring Boot Spring Boot make ...

随机推荐

  1. 设计模式之——迭代器模式

    设计模式是开发者前辈们给我们后背的一个经验总结.有效的使用设计模式,能够帮助我们编写可复用的类.所谓"可复用",就是指将类实现为一个组件,当一个组件发生改变时,不需要对其他组件进行 ...

  2. Gunner II--hdu5233(map&vector/二分)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5233 题意:有n颗树,第 i 棵树的高度为 h[i],树上有鸟,现在这个人要打m次枪,每次打的高度是 ...

  3. git提交到远程虚拟机

    git到自己的虚拟机中第一步:打通git(一)Linux中(ip为10.1.8.1)1.安装git如:Ubuntu中安装gitapt install git 2.Ubuntu中添加git用户sudo ...

  4. (2.4)备份与还原--WAL与备份原理

    预写式日志(Write-Ahead Logging (WAL))  部分转自:http://www.cnblogs.com/wenBlog/p/4423497.html SQL Server中使用了W ...

  5. Art of Android Develop. Activity的生命周期和启动模式。

    1.  onCreate() ,  onRestart(),  onStart(),  onResume(),  onPause(),  onStop(),  onDestroy() 2.

  6. DiskLruCache详解 From GuoLin Blogs.

    作者:郭霖老师,<第一行代码>作者,开源框架LitePal作者 http://blog.csdn.net/guolin_blog/article/details/28863651 概述 记 ...

  7. java生成多位随机数方法

    Math.random()方法可以令系统随机选取大于等于0.0且小于1.0的伪随机double值 利用函数Math.random()即可生成若干位随机数 以下是生成十位随机数代码: public st ...

  8. Apache Spark 2.0三种API的传说:RDD、DataFrame和Dataset

    Apache Spark吸引广大社区开发者的一个重要原因是:Apache Spark提供极其简单.易用的APIs,支持跨多种语言(比如:Scala.Java.Python和R)来操作大数据. 本文主要 ...

  9. mysql 系统变量和session变量

    mysql系统变量包括全局变量(global)和会话变量(session),global变量对所有session生效,session变量包括global变量.mysql调优必然会涉及这些系统变量的调整 ...

  10. 8种主要排序算法的C#实现 (一)

    简介 排序算法是我们编程中遇到的最多的算法.目前主流的算法有8种. 平均时间复杂度从高到低依次是: 冒泡排序(o(n2)),选择排序(o(n2)),插入排序(o(n2)),堆排序(o(nlogn)), ...