@RepositoryRestResource注解的使用

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
  }
}
原文地址:https://www.cnblogs.com/ScvQ/p/6897311.html