Springboot + Spring MVC大大简化了Web应用的RESTful开发,而Spring DataREST更简单。Spring Data REST是建立在DataRepository之上的,它能直接把resository以HATEOAS风格暴露成Web服务,而不需要再手写Controller层。
Springboot + Spring MVC
Web
RESTful
Spring DataREST
Spring Data REST
DataRepository
resository
HATEOAS
Controller
HATEOAS,即 Hypermedia as the Engine of Application State ,它是一种更成熟的REST模型,在资源的表达中包含了链接信息,客户端可以根据链接来发现可执行的动作。
REST
Spring Data REST支持Spring Data JPA、Spring Data MongoDB、Spring Data Neo4j、Spring Data GenFire、Spring Data Cassandra,这里选择大家比较熟悉的JPA。
Spring Data JPA
Spring Data MongoDB
Spring Data Neo4j
Spring Data GenFire
Spring Data Cassandra
JPA
我们用例子来感受一下吧。
我们通过Spring Initializr来快速创建Springboot项目。选中的依赖组件如下:
Springboot
Spring Web
Rest Repositories
Repository
H2 Database
H2
导入后对应的pom.xml中依赖如下:
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>
创建一个实体类User,如下所示:
User
package com.pkslow.rest.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; private Integer age; private String email; //getter & setter }
定义Repository接口用于操作数据库,如下所示:
package com.pkslow.rest.repo; import com.pkslow.rest.entity.User; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(path = "user") public interface UserRepository extends CrudRepository<User, Integer> { }
注解RepositoryRestResource是Data REST用于暴露Repository,path为访问路径,设置为user,则访问地址为http://localhost:8080/user。
RepositoryRestResource
Data REST
path
user
http://localhost:8080/user
准备好以上代码,直接启动Springboot应用即可,我们把端口设置为8080,访问如下:
8080
我们用Postman做一个基本操作。
Postman
新增:
查询:
通过主键ID查询:
ID
修改:
删除:
不难发现,返回的Json都带有链接,这就是HATEOAS风格。
Json
可以快速实现分页及排序功能,只需要把Repository的父接口改为PagingAndSortingRepository即可,如下所示:
PagingAndSortingRepository
@RepositoryRestResource(path = "user") public interface UserRepository extends PagingAndSortingRepository<User, Integer> { }
其实就是多了两个方法findAll(Sort var1)和findAll(Pageable var1),如下所示:
findAll(Sort var1)
findAll(Pageable var1)
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> { Iterable<T> findAll(Sort var1); Page<T> findAll(Pageable var1); }
查询http://localhost:8080/user?page=1&size=2&sort=id,desc,表示查询第二页,每页2条记录,以ID倒序展示。如下:
http://localhost:8080/user?page=1&size=2&sort=id,desc
{ "_embedded": { "users": [ { "name": "pkslow.com", "age": 18, "email": "pkslow@pkslow.com", "_links": { "self": { "href": "http://localhost:8080/user/33" }, "user": { "href": "http://localhost:8080/user/33" } } }, { "name": "pkslow.com", "age": 18, "email": "pkslow@pkslow.com", "_links": { "self": { "href": "http://localhost:8080/user/32" }, "user": { "href": "http://localhost:8080/user/32" } } } ] }, "_links": { "first": { "href": "http://localhost:8080/user?page=0&size=2&sort=id,desc" }, "prev": { "href": "http://localhost:8080/user?page=0&size=2&sort=id,desc" }, "self": { "href": "http://localhost:8080/user?page=1&size=2&sort=id,desc" }, "next": { "href": "http://localhost:8080/user?page=2&size=2&sort=id,desc" }, "last": { "href": "http://localhost:8080/user?page=17&size=2&sort=id,desc" }, "profile": { "href": "http://localhost:8080/profile/user" } }, "page": { "size": 2, "totalElements": 35, "totalPages": 18, "number": 1 } }
可以发现page是从0开始的,1表示第二页;返回结果还提供了第一页、上一页、本页、下一页、最后一页的链接;以及分页信息。
page
0
1
REST提供了8个基于Repository的事件,如下:
BeforeCreateEvent
AfterCreateEvent
BeforeSaveEvent
AfterSaveEvent
BeforeLinkSaveEvent
AfterLinkSaveEvent
BeforeDeleteEvent
AfterDeleteEvent
添加一个自定义事件如下:
package com.pkslow.rest.event; import com.pkslow.rest.entity.User; import org.springframework.data.rest.core.event.AbstractRepositoryEventListener; import org.springframework.stereotype.Component; @Component public class PkslowEventListener extends AbstractRepositoryEventListener<User> { @Override public void onBeforeCreate(User entity) { System.out.println("pkslow creating:" + entity); } @Override public void onBeforeSave(User entity) { System.out.println("pkslow saving:" + entity); } @Override public void onAfterDelete(User entity) { System.out.println("pkslow deleted:" + entity); } }
分别执行了增加、修改、删除后,日志如下:
pkslow creating:User{id=null, name='pkslow.com', age=18, email='pkslow@pkslow.com'} pkslow saving:User{id=32, name='pkslow.com', age=20, email='pkslow@pkslow.com'} pkslow deleted:User{id=14, name='pkslow.com', age=18, email='pkslow@pkslow.com'}
说明事件成功执行,结合这个功能,可以实现很多业务逻辑,如删除后记录操作日志,并删除其它相关数据。
默认基础路径是/,可以通过spring.data.rest.base- path=api进行配置,这样就变成了localhost:8080/api/user。
/
spring.data.rest.base- path=api
localhost:8080/api/user
HAL Browser是一个专门用于浏览基于JSON Hypertext Application Language的前端工具。我们前面已经提供了HATEOAS风格的RESTful服务,HAL Browser可以方便查看。
JSON Hypertext Application Language
HAL Browser
加入依赖:
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-rest-hal-browser</artifactId> <version>3.3.2.RELEASE</version> </dependency>
启动后访问http://localhost:8080/browser/index.html#/如下:
http://localhost:8080/browser/index.html#/
可以进行CRUD操作,具体就不一一展示了。
CRUD
原文链接:https://www.cnblogs.com/larrydpk/p/13456402.html