Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Author’s other platforms:

| CSDN:blog.csdn.net/qq_4115394…

| the nuggets: juejin. Cn/user / 651387…

| zhihu: www.zhihu.com/people/1024…

| GitHub:github.com/JiangXia-10…

| public no. : 1024 notes

This article is about 10,869 words and takes 30 minutes to read

One, foreword

We all know SpringBoot has made it easier and faster to develop Web projects. I wrote an article on how to quickly build a Springboot project: SpringBoot Getting Started: Build your first Springboot project using IDEA and Eclipse. This article will introduce how to develop Restful interface implementation to CRUD function based on SpringBoot.

Second, the concept of

What is a SpringBoot


Spring Boot is a new framework from the Pivotal team designed to simplify the initial setup and development process for new Spring applications. The framework uses a specific way to configure so that developers no longer need to define boilerplate configurations.

Simply put, you can develop projects quickly with a few jars and some simple configuration. To quote from the SpringBoot book:

There's no configuration, no web.xml, no build instructions, not even an application server, but that's the whole application. SpringBoot takes care of all the logistics of executing the application. You just have to figure out the code for the application.Copy the code

If we want to simply develop an external interface, all we need is the following code.

A main program launches the springBoot—- core

@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Copy the code

Control layer code:

@RestController public class HelloController { @RequestMapping("/hello") public String hello() { return "Hello World"; }}Copy the code

Success after the start of the main program, writing control layer, and then in the browser type http://localhost:8080//hello can view the information.

What is Restful interface

Representational State Transfer (Restful) apis are a software architecture style that provides a set of design principles and constraints rather than standards. It is mainly used for client and server interaction class software. Software designed in this style can be simpler, more hierarchical, and easier to implement mechanisms such as caching.

In Restful style, users request the same URL in the request mode: GET, POST, delete, PUT… In this way, the front-end developers will not be confused about the resource address of the request and a lot of trouble to check the method name, so as to form a unified interface.

Restful interfaces are defined as follows

GET (SELECT) : queries from the server. You can differentiate the query methods based on request parameters.

POST (CREATE) : Creates a resource on the server and invokes the INSERT operation.

PUT (UPDATE) : Updates resources on the server, invoking the UPDATE operation.

PATCH (UPDATE) : Updates resources on the server (the client provides the changed properties).

DELETE (DELETE) : Deletes the resource from the server, invoking the DELETE statement.

Three, actual combat – based on SpringBoot to develop a Restful interface

1. Preparation before development

1.1 Adding Dependencies

Here my related POM file configuration is as follows:

<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.3.2. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <groupId>com.springboot</groupId> <artifactId>springbootdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <name> Springbootdemo </name> <description>Demo project for Spring Boot</description> < properties > < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > < Java version > 1.8 < / Java version > </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</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-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <! <dependency> <groupId>org.mybatis. Boot </groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 1.2.0 < / version > < / dependency > <! --> <dependency> <groupId> MySQL </groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> </dependencies> <build> <plugins> <! Spring-boot-devtools restarts automatically when a file in the classpath changes. --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build> </project>Copy the code

1.2 Creating related databases and tables

MySql > create table user; MySql > create table user; MySql > create table user

CREATE TABLE `user` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
 `email` varchar(255) NOT NULL COMMENT '邮箱',
 `password` varchar(255) NOT NULL COMMENT '密码',
 `username` varchar(255) NOT NULL COMMENT '姓名',
 PRIMARY KEY (`id`),
 UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Copy the code

Insert data into table;

INSERT INTO 'user' VALUES ('1', '[email protected]', '123456', '123456'); INSERT INTO 'user' VALUES ('2', '[email protected]', '234567'); INSERT INTO ` user ` VALUES (' 3 ', '3 @qq.com', '345678', 'Cathy');Copy the code

1.3 Database Configuration Files

You then need to use application.properties to do some custom configuration, such as connection configuration for the data source, and so on. The configuration file I have here is as follows:

# # data source configuration spring. The datasource. Url = JDBC: mysql: / / localhost: 3306 / JDBC? useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=123456 Spring.datasource. Driver-class-name = com.mysql.jdbc.driver ## Mybatis config # com.pancm.bean to point to the entity class package path. Mybatis. TypeAliasesPackage = com. Springboot. # bean configuration for the classpath directory path mapper package, * representatives will scan all the XML document. mybatis.mapperLocations=classpath\:mapper/*.xmlCopy the code

2, actual combat development – code logic

After successfully creating the database, data tables, and downloading the corresponding JAR packages, configuration files, etc. Next, the formal development of the SpringBoot project.

2.1 entity class

SQL > create table user (bean, bean, bean, bean, bean, bean, bean, bean, bean, bean, bean, bean, bean, bean);

package com.springboot.springbootdemo.bean; public class User { private long id; private String email; private String password; private String username; public long getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }}Copy the code

2.2 Dao layer code logic

In dao layer logic, Hibernate and Mybatis generally have two ways to implement DATABASE CRUD:

The first is mapper configuration of XML.

The second is to use annotations, @insert, @select, @update, @delete, etc.

Here I use Spring’s JPA for basic add, delete, change and review, also based on annotations. For details on how SpringBoot can integrate JPA, see this article: SpringBoot integrates JPA for data access

First, create a NEW DAO package and create an interface under the DAO package named UserDao. The code is as follows:

package com.springboot.springbootdemo.dao; import com.springboot.springbootdemo.bean.User; import org.apache.ibatis.annotations.*; import java.util.List; @mapper public Interface UserDao {/** * new data */ @insert (" Insert into ") user(id,email,password,username) values (#{id},#{email},#{password},#{username})") void addUser(User user); */ @update (" Update user set username=#{username},password=#{password} where ID =#{id}") void updateUser(user user); /** * Delete data */ @delete (" Delete from user where id=#{id}") void deleteUser(int id); / * * * * * according to the id query data / @ the Select (" Select id, email, password, username from the user where the username = # {username} ") to the user findByName(@Param("userName") String userName); / * * * * / @ the Select query all data (" Select id, email, password, username FROM the user ") List < user > the.findall (); }Copy the code

Description:

  • Mapper: Adding this annotation to an interface indicates that the interface is CRUD based on annotation implementation.

  • Results: Map result set to be returned, where property represents the field of User class and column represents the corresponding

    Database fields.

  • Param: field of SQL condition.

  • Insert, Select, Update, Delete: add, query, modify, Delete the corresponding database.

2.3 Service Layer Logical layer

Create a service package with the userService interface and the UserServiceImpl class to implement the UserService interface.

UserService interface:

package com.springboot.springbootdemo.service; import com.springboot.springbootdemo.bean.User; import java.util.List; Public interface UserService {/** * new user * @param user * @return */ Boolean addUser(user user); /** * change user * @param user * @return */ Boolean updateUser(user user); /** * deleteUser * @param id * @return */ Boolean deleteUser(int id); @param userName */ User findUserByName(String userName); @return */ List<User> findAll(); }Copy the code

UserServiceImpl implementation class:

package com.springboot.springbootdemo.service; import com.springboot.springbootdemo.bean.User; import com.springboot.springbootdemo.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public boolean addUser(User user) { boolean flag=false; try{ userDao.addUser(user); flag=true; }catch(Exception e){ e.printStackTrace(); } return flag; } @Override public boolean updateUser(User user) { boolean flag=false; try{ userDao.updateUser(user); flag=true; }catch(Exception e){ e.printStackTrace(); } return flag; } @Override public boolean deleteUser(int id) { boolean flag=false; try{ userDao.deleteUser(id); flag=true; }catch(Exception e){ e.printStackTrace(); } return flag; } @Override public User findUserByName(String userName) { return userDao.findByName(userName); } @Override public List<User> findAll() { return userDao.findAll(); }}Copy the code

2.4 Controller Code logic of the control layer

Create a new Controller package and create a new UserController class as follows:

package com.springboot.springbootdemo.controller; import com.springboot.springbootdemo.bean.User; import com.springboot.springbootdemo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping(value = "/do/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/user", method = RequestMethod.POST) public boolean addUser(@RequestBody User user) { return userService.addUser(user); } @RequestMapping(value = "/user", method = RequestMethod.PUT) public boolean updateUser(@RequestBody User user) { return userService.updateUser(user); } @RequestMapping(value = "/user", method = RequestMethod.DELETE) public boolean delete(@RequestParam(value = "userId", required = true) int userId) { return userService.deleteUser(userId); } @RequestMapping(value = "/user", method = RequestMethod.GET) public User findByUserName(@RequestParam(value = "userName", required = true) String userName) { return userService.findUserByName(userName); } @RequestMapping(value = "/userAll", method = RequestMethod.GET) public List<User> findByUserAge() { return userService.findAll(); }}Copy the code

Description:

  • RestController: Methods in the default class are returned as JSON.

  • RequestMapping: Specifies the interface path.

  • Method: indicates the request format.

  • RequestParam: Request parameters.

  • RequestBody: this annotation defines the RequestBody content type and automatically parses the parameters into an instance of the class.

2.5 Application Main program

The following code is generated by default when a SpringBoot project is created:

package com.springboot.springbootdemo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.springboot.springbootdemo.dao") public class SpringbootdemoApplication { public static void main(String[] args) { SpringApplication.run(SpringbootdemoApplication.class, args); }}Copy the code

Description:

SpringApplication launches the Spring application’s classes from the main method. By default, it does the following: 1. Create an appropriate ApplicationContext instance (depending on the CLASspath). 2. Register a CommandLinePropertySource, so that the command line arguments as Spring properties. 3. Refresh the Application Context and load all singleton Beans. 4. Activate all CommandLineRunner Beans. Start the class directly with Main, and SpringBoot is automatically configured.

Some notes for this class:

SpringBootApplication: Enables component scanning and automatic configuration. MapperScan: indicates the configuration of scanning packets of the Mapper interface class

Three, test,

Once you’ve developed the code, test it to see if it works. Start the Application class first, and then use the Postman tool to test the interface, without writing the front-end code. In the actual development process, many projects now realize the separation of the front and back ends, so the front and back ends are generally developed separately, and the logic of the background usually needs to conduct interface testing by itself. We usually use Postman.

Postman = postman = postman = postman = postman = postman = postman

http://localhost:8080/do/user/userAll
Copy the code

Next test delete data:

http://localhost:8080/do/user/user?id=3
Copy the code

Data with id 3 has been deleted:

Test query data by name:

http://localhost:8080/do/user/user?userName= zhang SANCopy the code

Test update data:

http://localhost:8080/do/user/user
Copy the code

Mysql > update database (id 2);

Test new data:

http://localhost:8080/do/user/user
Copy the code

Add data with ID 3 to the database:

Fourth, the end

That’s all about springBoot developing a Restful interface, and the source code for this article has been synchronized to Github for download if necessary. Finally, if you think this article is good, just click “like” and “recommend” to more people.

Historical recommendation:

ElasticSearch: SpringBoot: ElasticSearch

Threads and common methods for threads

SpringBoot integrates JPA for data access

SpringBoot integration Druid configuration data source monitoring

SpringBoot integration Mybatis(top) : Annotated edition

SpringBoot integration Mybatis(below) : configuration version