Use SpringBoot to develop a Restful service for adding, deleting, modifying, and querying. springbootrestful

Source: Internet
Author: User

Use SpringBoot to develop a Restful service for adding, deleting, modifying, and querying. springbootrestful

Last year, I learned a little about SpringBoot from various channels and how it is convenient and convenient to develop web projects. However, I didn't study it seriously at the time. After all, I felt that I was not very familiar with Struts and SpringMVC. However, after reading a lot of Introduction to SpringBoot, it was not as difficult as you thought, so you started to prepare for learning SpringBoot. In my spare time, after reading SpringBoot practices and some blogs about SpringBoot, I started to write my first SpringBoot project. After some simple development of Restful interfaces for SpringBoot to implement the CRUD function, this blog post is available.

SpringBoot Introduction

Spring Boot is a new framework provided by the Pivotal team. It is designed to simplify the initial setup and development process of new Spring applications. The framework uses a specific method for configuration, so that developers no longer need to define the configuration of the template.

Simply put, you only need a few jar files and some simple configurations to quickly develop projects.

If I want to simply develop an external interface, I only need the following code.

A main program starts springBoot

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

Control Layer

@RestControllerpublic class HelloWorldController { @RequestMapping("/hello") public String index() {  return "Hello World"; } }

After the main program is successfully started, write the control layer and enter http: // localhost: 8080 // hello in the browser to view the information.

I feel that developing a program using SpringBoot is very simple!

In SpringBoot practice:

No configuration, no web. xml, no build instructions, or even no application server, but this is the whole application. SpringBoot will handle the various logistic work required to execute the application. You only need to handle the application code.

Developing a Restful Service Based on SpringBoot

Preparations should be made before developing the program.

I. Development Preparation1.1 databases and tables
Create database 'springboot'; USE 'springboot'; drop table if exists 't_ user'; create table 't_ user' ('id' int (11) not null AUTO_INCREMENT COMMENT 'id', 'name' varchar (10) default null comment 'name', 'age' int (2) default null comment 'age ', primary key ('id') ENGINE = InnoDB AUTO_INCREMENT = 12 default charset = utf8;

1.2 maven-related dependencies

SpringBoot's core jar

Spring-boot-starter: core module, including automatic configuration support, logs, and YAML;

<Parent> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-starter-parent </artifactId> <version> 1.5.9.RELEASE </version> <relativePath/> </parent> <properties> <project. build. sourceEncoding> UTF-8 </project. build. sourceEncoding> <java. version> 1.7 </java. version> <mybatis-spring-boot> 1.2.0 </mybatis-spring-boot> <mysql-connector> 5.1.39 </mysql-connector> </properties> <dependencies> <dep Endency> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-starter-web </artifactId> </dependency> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-starter-thymeleaf </artifactId> </dependency> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-starter-data-jpa </artifactId> </dependency> <groupId> org. springf Ramework. boot </groupId> <artifactId> spring-boot-devtools </artifactId> <optional> true </optional> </dependency> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-starter-test </artifactId> <scope> test </scope> </dependency> <! -- Spring Boot Mybatis dependency --> <dependency> <groupId> org. mybatis. spring. boot </groupId> <artifactId> mybatis-spring-boot-starter </artifactId> <version >$ {mybatis-spring-boot} </version> </dependency> <! -- MySQL connection driver dependency --> <dependency> <groupId> mysql </groupId> <artifactId> mysql-connector-java </artifactId> <version >$ {mysql-connector} </version> </dependency> </dependencies> <build> <plugins> <! -- Use the SpringBoot plug-in to use the spring-boot-devtools module. When the files in classpath change, the system automatically restarts! --> <Plugin> <groupId> org. springframework. boot </groupId> <artifactId> spring-boot-maven-plugin </artifactId> <configuration> <fork> true </fork> </configuration> </plugin> </ plugins> </build>
2. Engineering description 2.1 engineering structure diagram:

Com. pancm. web-Controller Layer
Com. pancm. dao-data operation layer DAO
Com. pancm. bean-entity class
Com. pancm. bean. service-business logic layer
Application-Application startup class
Application. properties-application configuration file. The configuration is automatically read when the application starts.

 

2.2 custom configuration file

Generally, we need some custom configurations, such as jdbc connection configuration. here we can use application. properties for configuration. The actual configuration of the data source is subject to your requirements.

# Configure spring. datasource. url = jdbc: mysql: // localhost: 3306/springBoot? UseUnicode = true & characterEncoding = utf8spring. datasource. username = rootspring. datasource. password = 123456spring. datasource. driver-class-name = com. mysql. jdbc. driver ## Mybatis configuration # Set to com. pancm. bean points to the object class package path. Mybatis. typeAliasesPackage = com. pancm. bean # configure it to the mapper package under the classpath path, and * scan all xml files. Mybatis. mapperLocations = classpath \: mapper/*. xml
Iii. Coding 3.1 compiling Pojo class users

The key code is coming soon.

We started to write the pojo class, which corresponds to the t_user table in the database.

The Code is as follows:

Public class User {/** no. */private int id;/** name */private String name;/** age */private int age; public User () {} public class User {/** no. */private int id;/** name */private String name;/** age */private int age; public User () {}// getter and setter omitted}
3.2 write the Dao Layer

In the previous Dao layer, both hibernate and mybatis can use annotations or mapper configuration files. Here we use spring JPA to complete CRUD.

Note:

There are two methods to implement CRUD with the database:

The first is the mapper configuration of xml.

The second method is to use annotations such as @ Insert, @ Select, @ Update, and @ Delete. This document uses the second

Import org. apache. ibatis. annotations. delete; import org. apache. ibatis. annotations. insert; import org. apache. ibatis. annotations. mapper; import org. apache. ibatis. annotations. result; import org. apache. ibatis. annotations. results; import org. apache. ibatis. annotations. select; import org. apache. ibatis. annotations. update; import org. springframework. data. repository. query. param; import com. pancm. bean. user; @ Mapperpublic interface UserDao {/*** new User data */@ Insert ("insert into t_user (id, name, age) values (# {id }, # {name}, # {age}) ") void addUser (User user User ); /*** modify user data */@ Update ("update t_user set name =#{ name}, age =#{ age} where id =#{ id }") void updateUser (User user User);/*** Delete user data */@ delete ("Delete from t_user where id = # {id}") void deleteUser (int id ); /*** query user information by user name **/@ Select ("SELECT id, name, age FROM t_user ") // return Map Result set @ Results ({@ Result (property = "id", column = "id"), @ Result (property = "name ", column = "name"), @ Result (property = "age", column = "age"),}) User findByName (@ Param ("name") String userName ); /*** query User information by User id **/@ Select ("SELECT id, name, age FROM t_user") User findById (@ Param ("id") int userId ); /*** query user information by user age */@ Select ("SELECT id, name, age FROM t_user where age = # {userAge }") user findByAge (int userAge );}

The annotations used for this interface are as follows:

Mapper: added this annotation to the interface to indicate that this interface is implemented based on the annotation.

Results: returned map result set. property indicates the fields of the User class, and column indicates the fields of the corresponding database.

Param: SQL condition field.

Insert, Select, Update, and Delete: add, query, modify, and Delete databases.

3.3 Service business logic layer

This is basically the same as hibernate and mybatis.

The Code is as follows:

Interface

Import com. pancm. bean. user;/***** Title: UserService * Description: User Interface * Version: 1.0.0 * @ author pancm * @ date July 15, January 9, 2018 */public interface UserService {/*** Add user * @ param User * @ return */boolean addUser (user ); /* ** modify user * @ param User * @ return */boolean updateUser (user ); /*** delete user * @ param id * @ return */boolean deleteUser (int id ); /*** query User information by userName * @ param userName */User findUserByName (String userName ); /*** query User information by User ID * @ param userId */User findUserById (int userId ); /*** query User information by User ID * @ param userAge */User findUserByAge (int userAge );}

Implementation class

Import org. springframework. beans. factory. annotation. autowired; import org. springframework. stereotype. service; import com. pancm. bean. user; import com. pancm. dao. userDao; import com. pancm. service. userService;/***** Title: UserServiceImpl * Description: * user operation implementation class * Version: 1.0.0 * @ author pancm * @ date March 13, January 9, 2018 */@ Servicepublic 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 User findUserById (int userId) {return userDao. findById (userId) ;}@ Override public User findUserByAge (int userAge) {return userDao. findByAge (userAge );}}
3.4 Controller control layer

The control layer is similar to springMVC, but it is much simpler than springMVC.

My personal understanding about the control layer annotation is as follows:

RestController: all methods in the default class are returned in json format.

RequestMapping: interface path configuration.

Method: request format.

RequestParam: request parameter.

The specific implementation is as follows:

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 com. pancm. bean. user; import com. pancm. service. userService;/***** Title: UserRestController * Description: * user data operation interface * Version: 1.0.0 * @ author pancm * @ date March 13, January 9, 2018 */@ RestController @ RequestMapping (value = "/api/user") public class UserRestController {@ Autowired private UserService userService; @ RequestMapping (value = "/addUser", method = RequestMethod. POST) public boolean addUser (User user) {System. out. println ("start to add... "); return userService. addUser (user) ;}@ RequestMapping (value = "/updateUser", method = RequestMethod. PUT) public boolean updateUser (User user) {System. out. println ("start updating... "); return userService. updateUser (user) ;}@ RequestMapping (value = "/deleteUser", method = RequestMethod. DELETE) public boolean delete (@ RequestParam (value = "userName", required = true) int userId) {System. out. println ("start to delete... "); return userService. deleteUser (userId) ;}@ RequestMapping (value = "/userName", method = RequestMethod. GET) public User findByUserName (@ RequestParam (value = "userName", required = true) String userName) {System. out. println ("START querying... "); return userService. findUserByName (userName);} @ RequestMapping (value = "/userId", method = RequestMethod. GET) public User findByUserId (@ RequestParam (value = "userId", required = true) int userId) {System. out. println ("START querying... "); return userService. findUserById (userId);} @ RequestMapping (value = "/userAge", method = RequestMethod. GET) public User findByUserAge (@ RequestParam (value = "userAge", required = true) int userAge) {System. out. println ("START querying... "); return userService. findUserById (userAge );}}
3.5 Application main program

SpringApplication is a class used to start Spring applications from the main method.

By default, it performs the following steps:

1. Create an appropriate ApplicationContext instance (depending on classpath ).

2. Register a CommandLinePropertySource to use the command line parameter as Spring properties.

3. Refresh the application context and load all Singleton beans.

4. Activate all CommandLineRunner beans.

Start this class directly using main, and SpringBoot will be automatically configured.

Ps: Even now, I still think this is really amazing.

Some annotations for this class. :

SpringBootApplication: Enable component scanning and automatic configuration.

MapperScan: mapper Interface Class scan package Configuration

The Code is as follows:

Import org. mybatis. spring. annotation. mapperScan; import org. springframework. boot. springApplication; import org. springframework. boot. autoconfigure. springBootApplication;/***** Title: Application * Description: * springBoot main program * Version: 1.0.0 * @ author pancm * @ date January 5, 2018 */@ SpringBootApplication @ MapperScan ("com. pancm. dao ") public class Application {public static void main (String [] args) {// start embedded Tomcat and initialize Spring environment and SpringApplication of various Spring components. run (Application. class, args); System. out. println ("the program is running... ");}}
Iv. Code Testing

After the code is compiled, we test the code.

After the Application is started, use the postman tool to test the interface.

The test results are as follows:

Only one get and post test is used here. The actual method has been tested, but it does not feel necessary.

I put the project on github:

Https://github.com/xuwujing/springBoot

Summary

The above section describes how to develop a Restful Service Based on SpringBoot to implement addition, deletion, modification, and query functions. I hope it will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.