初入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 ...
随机推荐
- [SQL Database] 内外网数据库同步
Azure SQL Azure(十) SQL Azure Data Sync数据同步功能(上) SQL Azure(十一) SQL Azure Data Sync数据同步功能(下) 走近微软云:SQL ...
- 前端开发 - JQuery - 下
二十五.jquery的事件 <!DOCTYPE html> <html lang="en"> <head> <meta charset=& ...
- python模块之PIL模块(生成随机验证码图片)
PIL简介 什么是PIL PIL:是Python Image Library的缩写,图像处理的模块.主要的类包括Image,ImageFont,ImageDraw,ImageFilter PIL的导入 ...
- redis哨兵集群、docker入门
redis-sentinel主从复制高可用 Redis-Sentinel Redis-Sentinel是redis官方推荐的高可用性解决方案,当用redis作master-slave的高可用时,如果m ...
- H5开发APP入门
一.MUI MUI是一个最接近原生APP体验的高性能前端框架.我们用它来排版布局. 官方网站:http://dev.dcloud.net.cn/mui/ 二.HTML5PLUS html5+是HBul ...
- git别名
git config --global alias.lg 'log --oneline --all --graph --decorate'
- IT开发工程师的悲哀现状和可能前途
IT开发工程师的悲哀现状和可能前途 本文所指的开发工程师,仅指程序开发人员和以数字电路开发为主的电子工程师.当你选择计算机或者电子.自控等专业进入大学时,你本来还是有机会从事其它行业的,可你毕业时执迷 ...
- Mac 升级 OpenSSL
[转载自 https://blog.csdn.net/focusjava/article/details/51179297 ] [升级Mac的openssl] 终端下 openssl version ...
- PHPcms v9 get标签sql 语句limit无效问题的解决方法
get标签非常好用,自定义模型后get几乎变成万能的了.但是PHPCMS升级到V9后,把2008的很多功能都去掉了,比如get标签中,在后面自动添加了一个LIMIT 0,20,这样你即使写了num=' ...
- 使用Echarts进行可视化的数据线呈现
由于游戏后台需要统计游戏玩家的支付情况,恰好那天看见同学群里聊天说到了Echarts,于是我就看了眼,一看,哟,还是百度的产品,看了文档,示例,确实很屌的样子啊,于是自己就开始试了,最终效果如下: 个 ...