Develop a Restful service based on SpringBoot to realize the function of adding, deleting, modifying and checking

foreword

Last year, I learned a little about SpringBoot from various channels, how convenient and fast it is when developing web projects. But I didn't study it seriously at that time. After all, I felt that I was not very proficient in Struts and SpringMVC. However, after reading a lot of introductions about SpringBoot, it is not as difficult as I imagined, so I began to prepare to learn SpringBoot. In my spare time, I started to write my first SpringBoot project after reading SpringBoot's actual combat and some great gods' blogs about SpringBoot. After being able to do some simple development of Restful-style interfaces to SpringBoot to implement CRUD functions, this blog post is here.

Introduction to SpringBoot

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 way to configure, so that developers no longer need to define boilerplate configuration.
Simply put, with just a few jars and some simple configuration, you can quickly develop your project.
If I just want to simply develop an external interface, then I only need the following code.

A main program starts springBoot

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

control layer

@RestController
public 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.

It feels very simple to use SpringBoot to develop programs!
In the words of SpringBoot's actual combat:

There's no configuration, no web.xml, no build instructions, or even an app server, but that's about it for the whole application. SpringBoot takes care of all the logistics required to execute the application, you just need to handle the application code.

Develop a Restful service based on SpringBoot

1. Development preparation

1.1 Databases and Tables

First, we need to create a database and a table in MySql
. The name of the database is springboot and the name of the table is t_user.
The script is as follows:

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

Because we use Maven to create, we need to add SpringBoot related shelf packages.
The Maven configuration here is as follows:
springBoot's core jar
spring-boot-starter : core modules, including auto-configuration support, logging, 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>
        <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>


          <!-- Spring Boot Mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot}</version>
        </dependency>

        <!-- MySQL 连接驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector}</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
        <!--运用SpringBoot 插件  使用spring-boot-devtools模块的应用,当classpath中的文件有改变时,会自动重启! -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>  

2. Engineering description

After successfully creating the database and downloading the corresponding rack package.
Let's officially develop the SpringBoot project.

2.1 Engineering structure diagram:

First determine the project structure, here I will briefly explain.

com.pancm.web - Controller 层
com.pancm.dao - 数据操作层 DAO
com.pancm.bean - 实体类
com.pancm.service - 业务逻辑层
Application - 应用启动类
application.properties - 应用配置文件,应用启动会自动读取配置

write picture description here

2.2 Custom configuration file

Generally, we need some custom configuration, such as configuring the connection configuration of jdbc, where we can use application.properties to configure. The actual configuration of the data source is subject to your own.

## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.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

3. Code writing

After creating the relevant project directory, we start to write the corresponding code.

3.1 Entity class writing

Since we are only here for testing, we only create a t_user table in the database, so here we only create a User entity class, and the fields in it correspond to the fields of the t_user table.

The sample 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 writing

In the previous Dao layer, both hibernate and mybatis can use annotations or mapper configuration files. Here we use spring's JPA to complete basic additions, deletions, and changes.
Note:
There are generally two ways to implement CRUD with the database:
the first is the mapper configuration of xml.
The second is to use annotations, @Insert, @Select, @Update, @Delete these are done. This article uses the second one.

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;

@Mapper
public interface UserDao {

    /**
     * 用户数据新增
     */
     @Insert("insert into t_user(id,name,age) values (#{id},#{name},#{age})")
      void addUser(User user); 

     /**
      * 用户数据修改
      */
     @Update("update t_user set name=#{name},age=#{age} where id=#{id}")
      void updateUser(User user);

     /**
      * 用户数据删除
     */
     @Delete("delete from t_user where id=#{id}")
     void deleteUser(int id);

      /**
     * 根据用户名称查询用户信息
     *
     */
    @Select("SELECT id,name,age FROM t_user where name=#{userName}")
    User findByName(@Param("userName") String userName);

    /**
     * 根据用户ID查询用户信息
     *
     */
    @Select("SELECT id,name,age FROM t_user where id=#{userId}")     
    User findById(@Param("userId") int userId);


    /**
     * 根据用户age查询用户信息
     */
    @Select("SELECT id,name,age FROM t_user where age = #{userAge}")     
    User findByAge(@Param("userAge") int userAge);

}

Description:
- mapper : This annotation is added to the interface to indicate that the interface is CRUD implemented based on the annotation.
- Results: The returned map result set, property represents the field of the User class, and column represents the field of the corresponding database.
- Param: The field of the sql condition.
- Insert, Select, Update, Delete: Corresponding database addition, search, modification and deletion.

3.3 Service business logic layer

This is basically the same as hibernate and mybatis.
code show as below:

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:
* 用户操作实现类 
* Version:1.0.0  
* @author pancm
* @date 2018年1月9日
 */
@Service
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 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 very similar to springMVC, but it is much simpler in comparison.
illustrate:

  • RestController: The methods in the default class will be 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: 
* 用户数据操作接口
* Version:1.0.0  
* @author pancm
* @date 2018年1月9日
 */
@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("开始新增...");
        return userService.addUser(user);
    }

    @RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
    public boolean updateUser( User user) {
        System.out.println("开始更新...");
        return userService.updateUser(user);
    }

    @RequestMapping(value = "/deleteUser", method = RequestMethod.DELETE)
    public boolean delete(@RequestParam(value = "userName", required = true) int userId) {
        System.out.println("开始删除...");
        return userService.deleteUser(userId);
    }

    @RequestMapping(value = "/userName", method = RequestMethod.GET)
    public User findByUserName(@RequestParam(value = "userName", required = true) String userName) {
        System.out.println("开始查询...");
        return userService.findUserByName(userName);
    }

    @RequestMapping(value = "/userId", method = RequestMethod.GET)
    public User findByUserId(@RequestParam(value = "userId", required = true) int userId) {
        System.out.println("开始查询...");
        return userService.findUserById(userId);
    }

    @RequestMapping(value = "/userAge", method = RequestMethod.GET)
    public User findByUserAge(@RequestParam(value = "userAge", required = true) int userAge) {
        System.out.println("开始查询...");
        return userService.findUserByAge(userAge);
    }
}

3.5 Application main program

SpringApplication is the class used to start the Spring application from the main method.
By default, it performs the following steps:
1. Creates an appropriate ApplicationContext instance (depending on the classpath).
2. Register a CommandLinePropertySource to take command line arguments as Spring properties.
3. Refresh the application context to load all singleton beans.
4. Activate all CommandLineRunner beans.
Start the class directly with main, and SpringBoot will automatically configure it.
ps: Even now I still think this is really amazing.

Some annotations for this class. :
SpringBootApplication: Enable component scanning and auto-configuration.
MapperScan: mapper interface class scan package configuration

code show as below:

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("程序正在运行...");
    }
}

Fourth, code testing

After the code is written, we test the code.
After starting the Application, use the postman tool to test the interface.
For the tutorial on using postman, see my blog: http://www.panchengming.com/2017/04/24/pancm12/

The test results are as follows:
write picture description here

write picture description here

Only one get and post test is used here, and the actual methods have been tested, but I feel that there is no need to map.
I put the project on github:
https://github.com/xuwujing/springBoot

If it feels good, I hope to give a star by the way.
This is the end of this article, thank you for reading.

Copyright statement:
Author: Nothingness
Blog Park Source: Garden Source: http://www.cnblogs.com/xuwujing
CSDN Source: http://blog.csdn.net/qazwsxpcm    
Personal Blog Source: http://www.panchengming.com
Original It's not easy, please indicate the source when reprinting, thank you!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325631215&siteId=291194637