初入spring boot(八 )Spring Data REST
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的更多相关文章
- Spring Boot(八):RabbitMQ详解
Spring Boot(八):RabbitMQ详解 RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用. 消息中间件在互联网公司的使用中越来越多 ...
- Spring Boot集成Spring Data Reids和Spring Session实现Session共享
首先,需要先集成Redis的支持,参考:http://www.cnblogs.com/EasonJim/p/7805665.html Spring Boot集成Spring Data Redis+Sp ...
- Spring Boot 结合Spring Data结合小项目(增,删,查,模糊查询,分页,排序)
本次做的小项目是类似于,公司发布招聘信息,因此有俩个表,一个公司表,一个招聘信息表,俩个表是一对多的关系 项目整体结构: Spring Boot和Spring Data结合的资源文件 applicat ...
- spring boot系列(五)spring boot 配置spring data jpa (查询方法)
接着上面spring boot系列(四)spring boot 配置spring data jpa 保存修改方法继续做查询的测试: 1 创建UserInfo实体类,代码和https://www.cnb ...
- Spring Boot 整合Spring Data JPA
Spring Boot整合Spring Data JPA 1)加入依赖 <dependency> <groupId>org.springframework.boot</g ...
- Spring Boot中Spring data注解的使用
文章目录 Spring Data Annotations @Transactional @NoRepositoryBean @Param @Id @Transient @CreatedBy, @Las ...
- Spring Boot 之Spring data JPA简介
文章目录 添加依赖 添加entity bean 创建 Dao Spring Data Configuration 测试 Spring Boot 之Spring data JPA简介 JPA的全称是Ja ...
- 一:Spring Boot、Spring Cloud
上次写了一篇文章叫Spring Cloud在国内中小型公司能用起来吗?介绍了Spring Cloud是否能在中小公司使用起来,这篇文章是它的姊妹篇.其实我们在这条路上已经走了一年多,从16年初到现在. ...
- 基于Spring Boot、Spring Cloud、Docker的微服务系统架构实践
由于最近公司业务需要,需要搭建基于Spring Cloud的微服务系统.遍访各大搜索引擎,发现国内资料少之又少,也难怪,国内Dubbo正统治着天下.但是,一个技术总有它的瓶颈,Dubbo也有它捉襟见肘 ...
- spring boot 与 spring cloud 关系
公司使用spring cloud,所以稍微了解一下 看了一下spring官网对 spring boot 以及 spring cloud 的解释 Spring Boot Spring Boot make ...
随机推荐
- PHP webservice 的初接触
webservice 现在是开始流行了,很多业务开启了这个功能.去年接触的一个金融类的项目有类似功能调用.当时没放心思研究,最两天试着接触了下,还真不错的.起步其实挺简单. 服务端的代码 server ...
- Yii2的主从数据库设置
项目做大了,数据库主从还是不可少的.使用Yii框架开发,如何设置数据库的主从呢?其实很简单. 先说一个主数据库服务器和多个从数据库服务器的情况,修改配置文件 config/db.php ,其中 sla ...
- HBase-MR
一.需求1:对一张表的rowkey进行计数 官方HBase-Mapreduce 需求1:对一张表的rowkey进行计数 1)导入环境变量 export HBASE_HOME=/root/hd/hbas ...
- mysql表的完整性约束
概览 为了防止不符合规范的数据进入数据库,在用户对数据进行插入.修改.删除等操作时,DBMS自动按照一定的约束条件对数据进行监测, 使不符合规范的数据不能进入数据库,以确保数据库中存储的数据正确.有效 ...
- Purpose of ContextLoaderListener in Spring
The ApplicationContext is where your Spring beans live. The purpose of the ContextLoaderListener is ...
- spring MVC学习(三)
1. @RequestMapping: 在请求的路径中传递参数:参数作为路径的一部分,可以在路径中直接使用 {paramName}来表示,另一种就是更加传统的表示方式?paramName=paramV ...
- linux 实用命令
从一台机器远程连接到另一台机器: ssh platform@192.168.155.116 从一台机器发送文件到另一台机器: scp /home/weihuang/vie-zyzj.jar platf ...
- Html5游戏开发-145行代码完成一个RPG小Demo
lufy前辈写过<[代码艺术]17行代码的贪吃蛇小游戏>一文,忽悠了不少求知的兄弟进去阅读,阅读量当然是相当的大.今天我不仿也搞一个这样的教程,目地不在于忽悠人,而在于帮助他人. 先看de ...
- Linux kernel 'mq_notify'内存错误引用漏洞
更新系统内核即可!参看http://www.cnblogs.com/peteremperor/p/9065998.html
- Lua4.0中getn陷阱
Lua4.0中getn潜规则 • 使用t[n] = nil方式删除元素会导致意外结果 t = {, , , , , , , , , }; t[] = nil; t = {, , , , , , , , ...