Develop a restful service based on Springboot to realize the function of adding and removing additions and deletions

Source: Internet
Author: User
Tags prepare

Objective

In the last year, in a variety of channels to understand the springboot, in the development of Web projects, how convenient and fast. But at that time did not seriously to study under, after all, feel oneself in struts and SPRINGMVC are used not too skilled. But after reading a lot about Springboot's introduction, and not so difficult to imagine, so began to prepare to learn springboot. In my spare time, after watching the Springboot combat and some of the great God of Springboot blog, began to write my first springboot project. This blog post is available after you can implement CRUD functionality with some simple development of the RESTful style interface for Springboot.

Springboot Introduction

Spring Boot is a new framework provided by the pivotal team designed to simplify the initial setup and development of new spring applications. The framework uses a specific approach to configuration, which eliminates the need for developers to define boilerplate configurations.
Simply put, you can quickly develop a project with just a few jars and some simple configuration.
If I want to simply develop an external interface, then you just 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 successfully starting the main program, write the control layer and then enter Http://localhost:8080//hello in the browser to view the information.

The feeling of using the Springboot development program is not very simple!
In Springboot combat, say:

There is no configuration, no web. XML, no build instructions, no application server, but this is the whole application. Springboot will take care of the various logistical tasks required to execute the application, as long as you take care of the application's code.

Developing a restful service based on Springboot

Before you develop the program, you should prepare it first

I. Development preparation 1.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 '姓名',  `age` int(2) DEFAULT NULL COMMENT '年龄',  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
1.2 Maven related dependencies

Springboot The most core jar
Spring-boot-starter: core modules, including automatic configuration support, logging, and yaml;

<parent> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter -parent</artifactid> <version>1.5.9.RELEASE</version> <relativePath/> </paren        T> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring- boot-starter-web</artifactid> </dependency> <dependency> &LT;GROUPID&GT;ORG.SPR Ingframework.boot</groupid> <artifactId>spring-boot-starter-thymeleaf</artifactId> &lt        ;/dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring- boot-starter-data-jpa</artifactid> </dependency> <dependency> &L             T;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</artifact Id> <scope>test</scope> </dependency> <!--Spring Boot Mybatis Dependent-<dependency> <groupId>org.mybatis.spring.boot</groupId> & Lt;artifactid>mybatis-spring-boot-starter</artifactid> <version>${mybatis-spring-boot}</versi On> </dependency> <!--MySQL Connection driver dependent-<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector}</versio n> </dependency> </dependencies> <build> <plugins> <!--use SPRI The Ngboot plugin uses the Spring-boot-devtools module application and automatically restarts when the files in the classpath are changed! -<plugin> <groupId>org.springframework.boot</groupId> &lt ;artifactid>spring-boot-maven-plugin</artifactid> <configuration> <for k>true</fork> </configuration> </plugin> </plugins> </bu   Ild>
Ii. Project Description 2.1 Engineering structure diagram:
com.pancm.web - Controller 层com.pancm.dao - 数据操作层 DAOcom.pancm.bean - 实体类com.pancm.bean.service - 业务逻辑层Application - 应用启动类application.properties - 应用配置文件,应用启动会自动读取配置

2.2 Custom configuration Files

In general we need some custom configurations, such as configuring the JDBC connection configuration, where we can configure it with application.properties . The actual configuration of the data source is subject to your reference.

## 数据源配置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 配置# 配置为 com.pancm.bean 指向实体类包路径。mybatis.typeAliasesPackage=com.pancm.bean# 配置为 classpath 路径下 mapper 包下,* 代表会扫描所有 xml 文件。mybatis.mapperLocations=classpath\:mapper/*.xml
Third, code writing

:

3.1 Pojo class User's writing

Come to the point of the code this is fast.
We start by writing the Pojo class, which corresponds to the T_user table in the database.
The code is as follows

 public class User {     /** 编号 */     private int id;     /** 姓名 */     private String name;          /** 年龄 */     private int age;          public User(){     }   public class User {     /** 编号 */     private int id;     /** 姓名 */     private String name;          /** 年龄 */     private int age;          public User(){     }//   getter和 setter 略 }
3.2 DAO Layer Authoring

In the previous DAO layer, hibernate and MyBatis can use annotations or use mapper configuration files. Here we use the spring JPA to complete the crud.

Description
There are generally two ways to implement CRUD with database implementations:
The first is the mapper configuration of XML.
The second is the use of annotations, @Insert, @Select, @Update, @Delete these to complete. This article uses the second type of

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 {/** * User data added */@Insert ("Insert into T_user (Id,na           Me,age) VALUES (#{id},#{name},#{age}) ") void AddUser (user user); /** * User Data modification */@Update ("Update t_user set Name=#{name},age=#{age} where Id=#{id}") void UpdateUser (use     R user);         /** * User Data deletion */@Delete ("Delete from T_user where Id=#{id}") void DeleteUser (int id);            /** * */@Select ("Select Id,name,age from T_user")//returns the MAP result set @Results ({ @Result (property = "id", column = "id"), @ResulT (property = ' name ', column = ' name '), @Result (property = ' age ', column = ' age '),}) User Findbyname (@Par       AM ("name") String UserName); /** * * */@Select ("Select Id,name,age from T_user") User FindByID (@Param ("id") int us            Erid);  /** * Query user information based on user age */@Select ("Select Id,name,age from t_user where age = #{userage}") User Findbyage (    int userage); }

The annotations used by this interface are personally understandable:
Mapper: Adding this annotation to the interface indicates that the interface is a crud based implementation of annotations.
Results: The map result set returned, property represents the field of the user class, and column represents the field of the corresponding database.
The field of the param:sql condition.
Insert, Select, Update, delete: The corresponding database of the increase, check, change, delete.

3.3 Service Business Logic Layer

This piece is the same as Hibernate and MyBatis.
The code is as follows:

Interface

import com.pancm.bean.User;/** * * Title: UserService* Description:用户接口 * Version:1.0.0  * @author pancm* @date 2018年1月9日 */public interface UserService {        /**     * 新增用户     * @param user     * @return     */    boolean addUser(User user);        /**     * 修改用户     * @param user     * @return     */    boolean updateUser(User user);            /**     * 删除用户     * @param id     * @return     */    boolean deleteUser(int id);         /**     * 根据用户名字查询用户信息     * @param userName     */    User findUserByName(String userName);        /**     * 根据用户ID查询用户信息     * @param userId     */    User findUserById(int userId);         /**     * 根据用户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 January 9, 2018 */@Servicepublic class Userservic            Eimpl 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 much like the SPRINGMVC, but it's a lot more concise than that.
Notes on the control layer the individual understands the following:

Restcontroller: 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 January 9, 2018 */@RestController @requestmapping (value = "/api/user") public class Userrestcontroller {@Autowired PR     Ivate UserService UserService; @RequestMapping (value = "/adduser", method = Requestmethod.post) Public boolean addUser (user user) {System.out        . println ("Start new ...");    return Userservice.adduser (user);        } @RequestMapping (value = "/updateuser", method = Requestmethod.put) Public boolean updateUser (user user) {        System.out.println ("Start update ..."); Return Userservice.updateuser(user); } @RequestMapping (value = "/deleteuser", method = Requestmethod.delete) Public boolean DELETE (@RequestParam (valu        E = "UserName", required = true) int userId) {System.out.println ("start delete ...");    Return Userservice.deleteuser (USERID); } @RequestMapping (value = "/username", method = requestmethod.get) public User findbyusername (@RequestParam (valu        E = "UserName", required = True) String userName) {System.out.println ("Start query ...");    Return Userservice.finduserbyname (UserName); } @RequestMapping (value = "/userid", method = requestmethod.get) public User Findbyuserid (@RequestParam (value =        "UserID", required = true) int userId) {System.out.println ("Start query ...");    Return Userservice.finduserbyid (USERID); } @RequestMapping (value = "/userage", method = requestmethod.get) public User findbyuserage (@RequestParam (value        = "Userage", required = true) int userage) {System.out.println ("Start query ..."); ReTurn Userservice.finduserbyid (userage); }}
3.5 Application Main Program

Springapplication is the class used to start the spring app from the main method.
By default, it performs the following steps:
1. Create an appropriate ApplicationContext instance (depending on the classpath).
2. Register a commandlinepropertysource to use the command-line arguments as spring properties.
3. Refresh application context to load all singleton beans.
4. Activate all Commandlinerunner beans.
Start the class directly using main, and the Springboot is automatically configured.
PS: Even now I still think this is really too powerful.

Some note descriptions for this class. :
Springbootapplication: Turn on 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 主程序 * Version:1.0.0  * @author pancm* @date 2018年1月5日 */@SpringBootApplication@MapperScan("com.pancm.dao")public class Application {    public static void main(String[] args) {        // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件        SpringApplication.run(Application.class, args);        System.out.println("程序正在运行...");    }}
Iv. Code Testing

When the code is written, we test the code.
After starting application, use the Postman tool to test the interface.
Postman the use of tutorials can read my blog: http://www.panchengming.com/2017/04/24/pancm12/

The test results are as follows:

Only one get and post tests have been used here, and the actual method has been tested, but it doesn't feel necessary to map it.
Project I put on GitHub:
Https://github.com/xuwujing/springBoot

If you feel good, I hope to give a star in the way.
To this end of this article, thank you for reading.

Copyright Notice:
Empty Realm
Blog Park Source: http://www.cnblogs.com/xuwujing
CSDN Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com
Original is not easy, reproduced please indicate the source, thank you!

Develop a restful service based on Springboot to realize the function of adding and removing additions and deletions

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.