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. 浅析pc机上如何将vmlinuz-2.6.31-14-generic解压出vmlinux

    浅析pc机上如何将vmlinuz-2.6.31-14-generic解压出vmlinux luther@gliethttp:~$ vim /boot/grub/grub.cfg 可以看到我们进入的系统 ...

  2. TCP粘包/拆包 ByteBuf和channel 如果没有Netty? 传统的多线程服务器,这个也是Apache处理请求的模式

    通俗地讲,Netty 能做什么? - 知乎 https://www.zhihu.com/question/24322387 谢邀.netty是一套在java NIO的基础上封装的便于用户开发网络应用程 ...

  3. A TCP connection is distinguished by four values

    4个值唯一地定义一条TCP连接. HTTP The Definitive Guide A computer might have several TCP connections open at any ...

  4. 搭建SpringbootAdmin监控中心报错A attempt was made to call the method reactor.retry.Retry.retryMax(I)Lreactor/ret)

    遇到了同样的错误,转载记录下: 转载自:https://blog.csdn.net/qq_41938882/article/details/85048953   很明显,还没有启动成功就报错了.报错原 ...

  5. 在HTML里面HEAD部分的META元素要表达的内容是什么

    1.name属性主要有以下几种参数: A.Keywords(关键字) 说明:keywords用来告诉搜索引擎你网页的关键字是什么. 举例:<meta name ="keywords&q ...

  6. SpringBoot 配置文件 YML/Profile

    1. 全局配置文件 application.properties application.yml 配置文件名是固定的; 配置文件存放在src/main/resources目录或者类路径/config下 ...

  7. What’s wrong with virtual methods called through an interface

    May 31, 2016 Calling a virtual method through an interface always was a lot slower than calling a st ...

  8. A Magic Lamp---hdu3183(链表删除| RMQ)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3183 给你一个长度<1000的数a,和m<len(a); 让把数a删除m个数字之后剩下的数 ...

  9. git学习------>如何汉化GitLab?

    在上一篇博客中,已经正常安装好了GitLab,然而全部界面都是纯英文的,为了照顾整个团队的英文水平,因此这篇博客的目的是将纯英文的GitLab进行汉化. 纯英文界面 第一步: 确认GitLab版本号 ...

  10. (3.15)常用知识-sql server分页

    推荐使用row_number over()方法,或2012以上使用offset PageSize = PageNumber = 方法一:(最常用的分页代码, top / not in) UserId ...