1 Preface
Welcome to visit Pumpkin speak slowly www.pkslow.com com Get more wonderful articles!
preface
Springboot + Spring MVC greatly simplifies the RESTful development of Web applications, while Spring Data REST is simpler. Spring Data REST is built on the Data Repository. It can directly expose the repository into Web services in HATEOAS style without the need to write the Controller layer.
HATEOAS, namely Hypermedia as the Engine of Application State, is a more mature REST model, which contains link information in the expression of resources, and the client can find executable actions according to the link.
Spring Data REST supports Spring Data JPA, Spring Data MongoDB, Spring Data Neo4j, Spring Data GenFire and Spring Data Cassandra. Here we choose the familiar JPA.
2 for example
Let's feel it with examples.
2.1 create project
We pass Spring Initializr To quickly create a Springboot project. The selected dependent components are as follows:
- (1) Spring Web: provide web services;
- (2) Rest Repositories: provide Spring Data REST support;
- (3) Spring Data JPA: provide Repository data access through JPA;
- (4) H2 Database: H2 Database, which is used for convenience and simplicity.
The corresponding POM after import The dependencies in XML are as follows:
<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>
2.2 entity class
Create an entity class User, as shown below:
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 }
2.3 definition of repository interface
Define the Repository interface to operate the database, as follows:
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> { }
Annotation: RepositoryRestResource is used by Data REST to expose the Repository. Path is the access path. If it is set to user, the access address is http://localhost:8080/user .
2.4 start access
Prepare the above code and directly start the Springboot application. We set the port to 8080. The access is as follows:
We use Postman to do a basic operation.
newly added:
Query:
Query by primary key ID:
Modification:
Delete:
It's not difficult to find that the returned Json has links, which is the HATEOAS style.
3 more exploration
3.1 paging and sorting functions
Paging and sorting functions can be realized quickly. You only need to change the parent interface of the Repository to pagingandsorting Repository, as shown below:
@RepositoryRestResource(path = "user") public interface UserRepository extends PagingAndSortingRepository<User, Integer> { }
In fact, there are two more methods findAll(Sort var1) and findAll(Pageable var1), as shown below:
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> { Iterable<T> findAll(Sort var1); Page<T> findAll(Pageable var1); }
query http://localhost:8080/user?page=1&size=2&sort=id , DESC, means to query the second page, with 2 records per page, displayed in reverse order of ID. As follows:
{ "_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 } }
It can be found that page starts from 0, and 1 indicates the second page; The return result also provides links to the first page, previous page, this page, next page and last page; And paging information.
3.2 event monitoring
REST provides eight Repository based events, as follows:
- BeforeCreateEvent
- AfterCreateEvent
- BeforeSaveEvent
- AfterSaveEvent
- BeforeLinkSaveEvent
- AfterLinkSaveEvent
- BeforeDeleteEvent
- AfterDeleteEvent
Add a custom event as follows:
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); } }
After adding, modifying and deleting respectively, the log is as follows:
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'}
It indicates that the event is successfully executed. Combined with this function, many business logic can be realized, such as recording the operation log after deletion and deleting other relevant data.
3.3 path
The default base path is /, which can be accessed through spring data. rest. Base path = API, so it becomes localhost:8080/api/user.
4 integrated HAL Browser view
HAL Browser Is a front-end tool for browsing JSON Hypertext Application Language. We have already provided the RESTful service of HATEOAS style, and the HAL Browser can be viewed easily.
Add dependency:
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-rest-hal-browser</artifactId> <version>3.3.2.RELEASE</version> </dependency>
Post startup access http://localhost:8080/browser/index.html#/ As follows:
CRUD operation can be carried out, which will not be shown one by one.
5 Summary
This article introduces Spring Data REST, which can facilitate RESTful service development. However, it is understood that not many are used in the project. A simple study is a way to understand Spring and its architecture concept.
The detailed code of this article can be obtained from the reply <springdatarest> of pumpkin slow talk official account.
Welcome to follow the wechat official account pumpkin talk, which will continue to update for you
Read more and share more; Write more and organize more.