Jun 01, 2021 Article blog
Springboot
and
Spring MVC
simplify
RESTful
development in
web
applications, but one simpler one is Spring
Spring Data REST
Spring Data REST
is built on
Data Repository
which
resository
directly to
Web
services in
HATEOAS
style without having to write the
Controller
layer.
HATEOAS
or
Hypermedia as the Engine of Application State
is a more mature
REST
model that includes link information in the expression of resources, and clients can discover executable actions based on links.
Spring Data REST
Spring Data JPA
Spring Data MongoDB
Spring Data Neo4j
Spring Data GenFire
Spring Data Cassandra
and choose the more familiar
JPA
here.
Let's take an example and feel it.
We quickly created the
Springboot
project with Spring
Spring Initializr
The selected dependent components are as follows:
Spring Data REST
Repository
data access through
JPA
(Recommended course: Spring tutorial)
The corresponding
pom.xml
after import depends on the following:
lt; d ependency& lt; g roupId&org.springframework.boot</groupId& lt; a rtifactId&spring-boot-starter-web</artifactId& lt;/dependency& lt; d ependency& lt; g roupId&org.springframework.boot</groupId& lt; a rtifactId&spring-boot-starter-data-jpa</artifactId& lt;/dependency& lt; d ependency& lt; g roupId&org.springframework.boot</groupId& lt; a rtifactId&spring-boot-starter-data-rest</artifactId& lt;/dependency& lt; d ependency& lt; g roupId&com.h2database</groupId& lt; a rtifactId&h2</artifactId& lt; scope&runtime</scope& lt;/dependency&
Create an entity class, User, as follows:
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
}
Define
Repository
interface for operating 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> {
}
Note
RepositoryRestResource
is
Data REST
used to expose
Repository
path
is the access path, is set to
user
and the access address is
http://localhost:8080/user
With the above code ready, just launch the
Springboot
app, and we set the port to 8080, with access as follows:
Let's do a basic operation with
Postman
It's not hard to see that the
Json
are linked, and that's
HATEOAS
style.
Paging and sorting can be implemented quickly by simply changing
Repository
parent interface to
PagingAndSortingRepository
@RepositoryRestResource(path = "user") public interface UserRepository extends PagingAndSortingRepository<User, Integer> { }
There are actually two more
findAll(Sort var1)
and
findAll(Pageable var1)
as follows:
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, indicating the second page of the query, 2 records per page, displayed in an ID. as follows:
{ "_embedded": { "users": [ { "name": "pkslow.com", "age": 18, "email": "[email protected]", "_links": { "self": { "href": " http://localhost:8080/user/33 " }, "user": { "href": " http://localhost:8080/user/33 " } } }, { "name": "pkslow.com", "age": 18, "email": "[email protected]", "_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 } }
You can find that
page
starts at 0, 1 represents the second page, and the return results provide links to the first, previous, current, next, and last pages, as well as paginated information.
(Recommended micro-class: Spring micro-class.) )
REST
provides eight
Repository
events, as follows:
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, the logs are as follows:
pkslow creating:User{id=null, name='pkslow.com', age=18, email='[email protected]'} pkslow saving:User{id=32, name='pkslow.com', age=20, email='[email protected]'} pkslow deleted:User{id=14, name='pkslow.com', age=18, email='[email protected]'}
Explaining the successful execution of the event, combined with this capability, enables many business logics, such as logging operations after deletion and deleting other related data.
(Recommended tutorial: Spring Boot those things.) )
The default underlying path is
/
, which can be configured by
spring.data.rest.base-path=api
which
localhost:8080/api/user
HAL Browser
is a front-end tool dedicated to browsing
JSON Hypertext Application Language
We've already provided
HATEOAS
RESTful
service that
HAL Browser
can easily view.
Join dependencies:
lt; d ependency& lt; g roupId&org.springframework.data</groupId& lt; a rtifactId&spring-data-rest-hal-browser</artifactId& lt; version&3.3.2.RELEASE</version& lt;/dependency&
The http://localhost:8080/browser/index.html#/ of post-start access are as follows:
CRUD
operations can be performed, as shown.
The above is about
Spring Data REST
introduction, it can be convenient for everyone to use
RESTful
development, I hope to help you, although the project is not a great opportunity to use, but also can expand some knowledge.