1、Build with Maven

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>org.springframework</groupId>
<artifactId>gs-accessing-data-rest</artifactId>
<version>0.1.0</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> <repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>

2、Create a domain object

目录:
src/main/java/hello/Person.java

代码:

package hello;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id; @Entity
public class Person { @Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id; private String firstName;
private String lastName; public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
}
}

Person有一个firstName和lastName,主键id配置成自动生成。

3、Create a Person repository

创建一个简单的repository类

package hello;

import java.util.List;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> { List<Person> findByLastName(@Param("name") String name); }

PersonRepository是一个继承PagingAndSortingRepository的interface,然后,你就可以对Person对象进行各种操作。

在程序运行的时候,Spring Data REST将自动创建此接口的实现。然后,它将使用@RepositoryRestResource注解让Spring MVC在/people处创建RESTful入口点。

在这里,您还可以加入一个自定义查询,传入lastName参数来检索Person对象的列表,稍后我会将介绍如何详细使用。

4、Make the application executable

目录:

src/main/java/hello/Application.java

代码:

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

这里就不需要我详细解释了吧?使用过SpringBoot的人基本知道了。

5、Test the application

运行这个Web程序,然后进入http://localhost:8080会显示如下信息:

$ curl http://localhost:8080

{
"_links" : {
"people" : {
"href" : "http://localhost:8080/people{?page,size,sort}",
"templated" : true
}
}
}

在这里你能看到服务器提供给你的基本信息,能看到刚才我们所定义的people所在地址http://localhost:8080/people,它还提供了一些选项:?page,?size,?sort

注意:Spring Data REST的JSON输出格式使用的是HAL格式。


现在我们进入这个URL地址:http://localhost:8080/people,看下服务器是如何输出的。

$ curl http://localhost:8080/people

{
"_links" : {
"self" : {
"href" : "http://localhost:8080/people{?page,size,sort}",
"templated" : true
},
"search" : {
"href" : "http://localhost:8080/people/search"
}
},
"page" : {
"size" : 20,
"totalElements" : 0,
"totalPages" : 0,
"number" : 0
}
}

由输出可见,数据库中暂无任何Person对象的信息,现在我们开始新建一个对象:

$ curl -i -X POST -H "Content-Type:application/json" -d '{  "firstName" : "Frodo",  "lastName" : "Baggins" }' http://localhost:8080/people

HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Location: http://localhost:8080/people/1
Content-Length: 0
Date: Wed, 13 Dec 2016 14:26:55 GMT

-i 显示请求头信息
-X POST : 利用POST创建一个新的实体
-H "Content-Type:application/json" : 设置内容类型, 让应用程序知道你要传输的内容是JSON还是XML
-d '{ "firstName" : "Frodo", "lastName" : "Baggins" }' 一个数据包,要发送给应用程序的数据。


$ curl http://localhost:8080/people

{
"_links" : {
"self" : {
"href" : "http://localhost:8080/people{?page,size,sort}",
"templated" : true
},
"search" : {
"href" : "http://localhost:8080/people/search"
}
},
"_embedded" : {
"persons" : [ {
"firstName" : "Frodo",
"lastName" : "Baggins",
"_links" : {
"self" : {
"href" : "http://localhost:8080/people/1"
}
}
} ]
},
"page" : {
"size" : 20,
"totalElements" : 1,
"totalPages" : 1,
"number" : 0
}
}

personsJSON数组现在就包含了所有Person对象的列表。其中也包含了这条消息的self连接地址,也就是你可以直接查询单个记录的详细信息,现在就让我们访问一下看下结果。

$ curl http://localhost:8080/people/1

{
"firstName" : "Frodo",
"lastName" : "Baggins",
"_links" : {
"self" : {
"href" : "http://localhost:8080/people/1"
}
}
}
查找所有自定义查询:

$ curl http://localhost:8080/people/search

{
"_links" : {
"findByLastName" : {
"href" : "http://localhost:8080/people/search/findByLastName{?name}",
"templated" : true
}
}
}

通过返回结果,我们能看见之前定义的findByLastName接口,给name参数传入一个值,就可以达到查询功能。

$ curl http://localhost:8080/people/search/findByLastName?name=Baggins

{
"_embedded" : {
"persons" : [ {
"firstName" : "Frodo",
"lastName" : "Baggins",
"_links" : {
"self" : {
"href" : "http://localhost:8080/people/1"
}
}
} ]
}
}

因为我们之前在代码里面定义的返回结果是一个List<Person>类型,所以它将返回所有符合条件的结果。如果你在代码里定义返回结果为Person,程序会选择一个Person对象进行返回。


除此之外,我们还可以使用PUTPATCHDELETE请求方式,来进行替换、更新或删除现有记录的操作

$ curl -X PUT -H "Content-Type:application/json" -d '{ "firstName": "Bilbo", "lastName": "Baggins" }' http://localhost:8080/people/1
$ curl http://localhost:8080/people/1 输出内容:
{
"firstName" : "Bilbo",
"lastName" : "Baggins",
"_links" : {
"self" : {
"href" : "http://localhost:8080/people/1"
}
}
}

$ curl -X PATCH -H "Content-Type:application/json" -d '{ "firstName": "Bilbo Jr." }' http://localhost:8080/people/1
$ curl http://localhost:8080/people/1 输出内容:

{
"firstName" : "Bilbo Jr.",
"lastName" : "Baggins",
"_links" : {
"self" : {
"href" : "http://localhost:8080/people/1"
}
}
}

注意:如果你使用PUT命令,它将替换整个记录,如果有字段没有提供值,它将置为null。PATCH反之。

你也可以删除记录:

$ curl -X DELETE http://localhost:8080/people/1
$ curl http://localhost:8080/people
{
"_links" : {
"self" : {
"href" : "http://localhost:8080/people{?page,size,sort}",
"templated" : true
},
"search" : {
"href" : "http://localhost:8080/people/search"
}
},
"page" : {
"size" : 20,
"totalElements" : 0,
"totalPages" : 0,
"number" : 0
}
}

@RepositoryRestResource注解的使用的更多相关文章

  1. Spring Boot 学习(2)

    文 by / 林本托 Tips 做一个终身学习的人. 源代码:github下的/code01/ch2. 配置 Web 应用程序 在上一章中,我们学习了如何创建一个基本的应用程序模板,并添加了一些基本功 ...

  2. SpringCloud的DataRest(一)

    一.概念与定义 Spring Data Rest 基于Spring Data的repository,可以把 repository 自动输出为REST资源, 这样做的好处: 可以免去大量的 contro ...

  3. spring-data-rest的魔力 10分钟实现增删改查

    目录 创建项目 启动项目 添加person 查看person 及 person 列表 条件查询 分页查询 controller 去哪里了 自定义 spring-data-rest 魔力之外的contr ...

  4. 初入spring boot(八 )Spring Data REST

    1. 什么是Spring Data REST Spring Data JPA是基于Spring Data 的Repository之上,可以将Repository自动输出为REST资源.目前Spring ...

  5. spring 、spring boot 常用注解

    @Profile 1.用户配置文件注解. 2.使用范围: @Configration 和 @Component 注解的类及其方法, 其中包括继承了 @Component 的注解: @Service. ...

  6. 基于spring注解AOP的异常处理

    一.前言 项目刚刚开发的时候,并没有做好充足的准备.开发到一定程度的时候才会想到还有一些问题没有解决.就比如今天我要说的一个问题:异常的处理.写程序的时候一般都会通过try...catch...fin ...

  7. [Spring]IoC容器之进击的注解

    先啰嗦两句: 第一次在博客园使用markdown编辑,感觉渲染样式差强人意,还是github的样式比较顺眼. 概述 Spring2.5 引入了注解. 于是,一个问题产生了:使用注解方式注入 JavaB ...

  8. Android注解使用之通过annotationProcessor注解生成代码实现自己的ButterKnife框架

    前言: Annotation注解在Android的开发中的使用越来越普遍,例如EventBus.ButterKnife.Dagger2等,之前使用注解的时候需要利用反射机制势必影响到运行效率及性能,直 ...

  9. Android注解使用之注解编译android-apt如何切换到annotationProcessor

    前言: 自从EventBus 3.x发布之后其通过注解预编译的方式解决了之前通过反射机制所引起的性能效率问题,其中注解预编译所采用的的就是android-apt的方式,不过最近Apt工具的作者宣布了不 ...

随机推荐

  1. JavaScript学习基础

    基本语法    JavaScript语法和Java语言类似,每个语句以 : 结束,语句块用 {...}包起来.JavaScript并不强制要求在每个语句的结尾加: ,但是建议都加上,不给自己找麻烦.  ...

  2. JQuery事件(2)

    jQuery 事件 下面是 jQuery 中事件方法的一些例子: Event 函数 绑定函数至 $(document).ready(function) 将函数绑定到文档的就绪事件(当文档完成加载时) ...

  3. Caffe常用算子GPU和CPU对比

    通过整理LeNet.AlexNet.VGG16.googLeNet.ResNet.MLP统计出的常用算子(不包括ReLU),表格是对比. Prelu Cpu版 Gpu版 for (int i = 0; ...

  4. MongoDB系列(三):增删改查(CURD)

    上篇讲了MongoDB的基础知识,大家应该对MongoDB有所了解了,当然真正用的还是curd操作,本篇为大家讲解MongoDB的curd操作. 1.数据库操作 #.增 use config #如果数 ...

  5. pamamiko的学习笔记

    pamamiko的学习笔记 Paramiko包含两个核心组件,一个为SSHClient类,另一个为SFTPClient类, 一,paramiko的连接有两种方式,一种是通过paramiko.SSHCl ...

  6. SQL SERVER 2012安装配置说明(多图详解)

    1. 优先安装软件 1. net framework3.5. 2. 在安装SQL SERVER 2012前需要3.5的支持.在WIN 2012系统可以在系统管理的添加角色和功能中安装,如下将[.NET ...

  7. 快读代码level.2

    long long read() { long long ans=0; char last=' ',ch=getchar();//last用来存正负号,并消去那些换行符,空格 ') { last=ch ...

  8. ios json数据null的处理

    此处我把json数据中的null转换成了@"",防止出现null程序崩掉,可以把下边宏代码复制到pch中,就可以在整个程序中引用了 #define DSStringValue(va ...

  9. 在JavaScript中,++在前和++在后有什么区别

    一.++可以与输出语句写在一起,++写在变量前和写在变量后不是一个意思++ i 和 i ++ 区别在于运算顺序和结合方向. 在JavaScript中有两种自加运算,其运算符均为 ++,功能为将运算符自 ...

  10. vue中前进刷新、后退缓存方案收集

    来源掘金: https://juejin.im/post/5b2ce07ce51d45588a7dbf76 来源博客园 https://www.cnblogs.com/wonyun/p/8763314 ...