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. 给NavigationBar设置颜色

    传统的设置 ) { [[UINavigationBar appearance] setBarTintColor:[UIColor redColor]]; } else { [[UINavigation ...

  2. textarea文本输入区内实现换行

    在文本间输入 即可成功换行 <textarea class="mytextarea">1.第一行 2.第二行 </textarea>

  3. 隐藏Apache、nginx和PHP的版本号的配置方法

    最近提示说有漏洞,暴露apache.nginx和php的版本号.网上搜了下,整理的方法如下: 首先说apache 在http.conf文件里添加下面两行,默认是没有的 ServerSignature ...

  4. 【opencv】ubuntu opencv imshow()报错

    错误提示: ubuntu opencv imshow() 报错 windows.cpp报错 the function is not implemented If you are on Ubuntu o ...

  5. vue监听浏览器窗口大小变化

    首先,页面初始化mounted的时候,通过 document.body.clientWidth 和 document.body.clientHeight 来获取到浏览器的宽和高,然后通过 window ...

  6. 关闭在chrome里使用双指前进后退页面的功能

    defaults write com.google.Chrome AppleEnableSwipeNavigateWithScrolls -bool FALSE

  7. 技术架构标杆(Certicom Security Architecture)对比思考——By Me at 20140408

    看到一家国外网络安全企业Certicom,官网链接:http://www.certicom.com/,可以作为很好的企业安全技术建构以及产品规划的标杆,下面我绘制了该公司的产品组合以及技术架构框图:

  8. 每人涨10%的工资,涨的前一共不超过5万,从低工资往高工资的人涨,超过5W则停止涨,问涨的钱花了多少,多少人获得了涨薪。

    ;with test(CID,money,NewAmount) as ( SELECT Row_Number() over ( order by money ) as CID ,money ,mone ...

  9. Linux PHP7的openssl扩展安装

    Linux环境下使用PHPmailer发送邮件时,出现如下错误: SMTP -> ERROR: Failed to connect to server: Unable to find the s ...

  10. 使用QJM构建HDFS HA架构(2.2+)

    转载自:http://blog.csdn.net/a822631129/article/details/51313145 本文主要介绍HDFS HA特性,以及如何使用QJM(Quorum Journa ...