什么是Spring Data REST
Spring Data REST是基于Spring Data的repository之上,可以把 repository 自动输出为REST资源,目前支持Spring Data JPA、Spring Data MongoDB、Spring Data Neo4j、Spring Data GemFire、Spring Data Cassandra的 repository 自动转换成REST服务。注意是自动。简单点说,Spring Data REST把我们需要编写的大量REST模版接口做了自动化实现。
实战
1:新建Spring Boot项目,添加依赖JPA和Rest Repositories,并导入数据库驱动
2:配置属性
application.properties
//数据源
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/book
spring.datasource.username=root
spring.datasource.password=123456
//JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent-output=true
实体类Person
@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;
}
}
实体类的Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
Person findByNameStartsWith(String name);
}
安装Postman
https://www.getpostman.com/
REST服务测试
列表:
获取单一对象(获得id为1的对象)
查询:
上面自定义实体类Repository中定义了findByNameStartsWith方法,若想此方法也暴露为REST资源,需要做如下修改:
//Spring Data REST默认规则是在实体类之后加上"s"来形成路径,我们可以通过@RepositoryRestResource注解的path属性进行修改!
@RepositoryRestResource(path = "people")
public interface PersonRepository extends JpaRepository<Person, Long> {
@RestResource(path = "nameStartsWith", rel = "nameStartsWith")
Person findByNameStartsWith(@Param("name")String name);
}
分页:
排序:
保存:
通过输出可以看出,保存成功后,我们的新数据的id为45;
更新(更新刚刚新增的id为45的数据):
删除(删除刚刚新增的id为45的数据):
此时再用GET方式访问id为45的数据:
表明所访问的REST资源不存在;
定制
定制根路径:
在上面的例子中,我们访问的REST资源的路径是在根目录下的,即http://localhost:8080/people,如果我们需要定制根路径的话,只需在application.properties下新增如下定义即可:
spring.data.rest.base-path=/api
此时REST资源的路径变成了http://localhost:8080/api/people;
定制节点路径:
Spring Data REST默认规则是在实体类之后加上"s"来形成路径,我们可以通过@RepositoryRestResource注解的path属性进行修改!
默认为http://localhost:8080/persons
@RepositoryRestResource(path = "people")
此时REST资源的路径变成了http://localhost:8080/people;
参考书籍:Spring Boot 实战
以上只是学习所做的笔记, 以供日后参考!!!