In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
I. introduction to Restful
REST is a style of Web software structure, not a standard. Matching or compatibility with this architecture style is called REST service. REST service is concise and hierarchical. REST is usually based on existing popular protocols and standards such as HTTP,URI, XML and HTML. In REST, resources are specified by URI, and the addition, deletion, modification and query of resources are also realized through POST,PUT,GET,DELETE and other methods provided by HTTP protocol. Using REST can make more efficient use of cache to improve response speed, and the communication session state in REST is maintained by the client, which allows different servers to handle different requests in a series of requests, thus improving the scalability of the server. In front-end separation projects, a good project must follow the REST architecture style.
In the Spring Mvc framework, developers can provide RestController annotations to develop a RESTful service, but Spring Boot provides an automated configuration solution, and developers only need to add related dependencies to quickly build a RESTful service.
II. Implementing REST with JPA
Using Spring Data JPA and Spring Data Rest in Spring Boot, you can quickly develop a RESTful service.
1. Basic realization
(1) create a project: create a Spring Boot project and add the following dependencies
Org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-data-rest org.springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime Com.alibaba druid 1.1.10 org.projectlombok lombok true
(2) in addition to adding database-related dependencies, there are also Spring Data Jpa and Spring Data Rest dependencies. After the project is completed, configure it in the configuration file as follows:
Server.port=8088spring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.url=jdbc:mysql://localhost:3306/spring_vue?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=falsespring.datasource.username=rootspring.datasource.password=*spring.jpa.hibernate.ddl-auto=updatespring.jpa.database=mysqlspring.jpa.show-sql=truespring.jpa.open-in-view=truespring.jpa.properties.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
two。 Create an entity class
@ Entity@Data@Table (name = "book") public class Book {@ Id @ GeneratedValue (strategy = GenerationType.IDENTITY) @ Column (name = "id") private Integer id; @ Column (name = "name") private String name; @ Column (name = "author") private String author; @ Column (name = "price") private float price;}
3. Create BookRepository
Public interface BookRepository extends JpaRepository, JpaSpecificationExecutor {}
(3) it inherits JpaRepository,JpaSpecificationExecutor and contains many ready-made methods to add, delete, modify and query in JpaRepository.
4. test
After the above steps, the simple RESTful architecture is complete, and then you can test it:
(1) add a test. After the Postman,RESTful we use here is successfully built, the default request path is the entity class name plus s. It is easy to add a piece of data to the database. Just initiate a post request and write the data to be added. Here, the data is in JSON format, as follows:
Summary: path: localhost:8088/books, format: JSON, request type: post
(2) Paging query test, the query is a Get request, and the paging query request path entity class lowercase plus s, here is / books. The default number of records per page for paging query is 20, and the number of pages is 0. The test is as follows:
Summary: request type GET, no parameters, path: localhost:8088/books
(3) according to id query, if you query based on id, you only need the suffix id after the path. The path is as follows:
Summary: path: localhost:8088/books/4, type: GET
(4) paging query expansion, adding the number of query pages, entries, and sorting, which only requires suffix parameters.
Summary: path: localhost:8088/books?page=1&size=3, request type: GET
In addition to paging, you can also add sorting as follows:
Summary: path: localhost:8088/books?page=1&size=3&sort=id,desc, type: GET
(5) to modify the test, you need to send a PUT request, because the modification is based on id, so you need to add id to the path, and then pass the modification data (in JSON format), as follows:
Summary: path: localhost:8088/books/15, as shown in the request parameter diagram, request type: PUT
(6) to delete a test, you can delete data using DELETE requests, such as deleting records with an id of 1. The route is as follows: localhost:8088/books/11
5. Custom request path
By default, the request path is the entity class name plus s. If the developer wants to redefine the path, it can be implemented by @ RepositoryResource annotation.
RepositoryRestResource (path= "bs", collectionResourceRel= "bs", itemResourceRel= "bs") public interface BookRepository extends JpaRepository, JpaSpecificationExecutor {}
Code explanation: @ RepositoryResource annotated path attribute indicates that the books in all request paths is modified to bs (localhost:8088/bs), and collectionResourceRel indicates that the key of the book collection in the returned book collection is modified to bs,itemResourceRel, which means that the key of a single book in the returned JSON collection is modified to b
6. Custom query method
The default query method supports paging query, sorting query and query by id. If the developer wants to query by a certain attribute, just define the relevant method in BookRepository and expose it. The code is as follows:
RepositoryRestResource (path = "bs") public interface BookRepository extends JpaRepository, JpaSpecificationExecutor {@ RestResource (path = "author", rel = "author") public List findByAuthor (@ Param ("author") String author);}
Code interpretation:
For a custom query, you only need to define the query method in BookRepository. After the method is defined, you can not add @ RestResource annotation. The default path is the method name. Take the above custom method as an example. If you do not add @ RestResource annotation, the default method call path is: localhost:8088/bs/search/findByAuthor?author= Jinyong. If you add comments, customize the method query path, where path is the latest path, as shown above. His visit path is: localhost:8088/bs/search//author?author= Jin Yong, as follows:
Note: users can query which query methods are exposed by visiting: localhost:8088/bs/search
7. Hiding method
(1) by default, classes that inherit the Repository API or its subclasses are exposed, that is, developers can perform basic add, delete, modify and query methods. If developers do not want to expose various methods of manipulating objects by this API class, they can configure as follows:
@ RepositoryRestResource (exported=false) public interface BookRepository extends JpaRepository, JpaSpecificationExecutor {}
In this way, all methods in this interface will fail.
(2) if you just do not want to expose a certain method, you can annotate the method @ RestResource and set exported=false in the note, so that the method will become invalid, as follows:
@ Override @ RestResource (exported=false) void deleteById (Integer id)
8. Configure CORS (cross-domain support)
All methods support cross-domain access. Annotate the interface with @ CrossOrigin as follows:
CrossOrigin@RepositoryRestResource (path = "bs") public interface BookRepository extends JpaRepository, JpaSpecificationExecutor {@ RestResource (path = "author", rel = "author") public List findByAuthor (@ Param ("author") String author);}
(2) some methods support cross-domain, and add @ CrossOrigin annotation to the method to be supported.
9. Other configuration
Developers can add common attributes to facilitate development, as follows:
Spring.data.rest.default-page-size=2spring.data.rest.page-param-name=pathspring.data.rest.sort-param-name=sortspring.data.rest.limit-param-name=sizespring.data.rest.base-path=/apispring.data.rest.return-body-on-create=truespring.data.rest.return-body-on-update=true
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.