SpringBoot for add-delete check -- Restful style

Posted by cgm225 on Sat, 07 Sep 2019 05:04:18 +0200

Preface

Last year, I learned a little about Spring Boot from a variety of sources, how easy and fast it is to develop web projects.But at that time, I didn't study hard, after all, I didn't feel very skilled in Struts and Spring MVC.But after reading a lot about Spring Boot, it was not as difficult as I thought, so I started preparing to learn Spring Boot.

In my spare time, after reading the actual Spring Boot battle and some of the Gods'blogs about Spring Boot, I started writing my first Spring Boot project.This blog post comes after some simple development of Restful-style interfaces for Spring Boot to implement CRUD functionality.

Introduction to Spring Boot

Spring Boot is a new framework provided by the Pivotal team and is designed to simplify the initial build and development of new Spring applications.The framework is configured in a specific way so that developers no longer need to define a template configuration.

Simply put, you can quickly develop a project with just a few jar s and a few simple configurations.

If I want to simply develop an external interface, I just 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 launching the main program, write the control layer and enter it in the browser http://localhost : 8080//hello to view the information.

Feel like using the SpringBoot development program is not that easy!

In SpringBoot's words:

There is no configuration, no web.xml, no build instructions, or even no application server, but this is the entire application.SpringBoot does all the logistical work you need to do to execute your application. All you have to do is figure out the application's code.

Developing a Restful Service based on SpringBoot

1. Preparation for Development

1.1 Databases and Tables

First, we need to create a database and a table in MySql

The database name is springboot and the table name 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 'Full name',
         `age` int(2) DEFAULT NULL COMMENT 'Age',
         PRIMARY KEY (`id`)
        ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
       

1.2 maven dependent

Because we created it using Maven, we need to add the related SpringBoot shelf packages.

Here Maven is configured as follows:

The core jar of springBoot
spring-boot-starter: Core modules, including automatic configuration support, logging, and YAML;


       <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 rely on -->
         <dependency>
         <groupId>org.mybatis.spring.boot</groupId>
         <artifactId>mybatis-spring-boot-starter</artifactId>
         <version>${mybatis-spring-boot}</version>
         </dependency>
        


         <!-- MySQL Connection Driven Dependency -->
         <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>${mysql-connector}</version>
         </dependency>
         </dependencies>
       

2. Project description

After successfully creating the database and downloading the appropriate shelf packages.

Let's formally develop the SpringBoot project.

2.1 Engineering structure drawing:

First of all, determine the structure of the project, and here I'll explain it briefly.

com.pancm.web - Controller layer
com.pancm.dao - Data Operations Layer DAO
com.pancm.bean - Entity class
com.pancm.service - Business logic layer
Application - Apply Startup Class
application.properties - Apply configuration file, application startup reads configuration automatically

2.2 Custom Profile

In general, we need some custom configurations, such as configuring the connection configuration for jdbc, where we can configure it with application.properties.The actual configuration of the data source is yours.

        ## Data Source Configuration
        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 Configuration
        # Configure com.pancm.bean to point to the entity class package path.
        mybatis.typeAliasesPackage=com.pancm.bean
        # Configured under the mapper package in the classpath path path, * will scan all xml files.
        mybatis.mapperLocations=classpath\:mapper/*.xml
       

3. Coding

Once you've created a catalog of related projects, we're ready to write the code.

3.1 Entity Class Writing

Since we're just testing, we've only created one t_user table in the database, so here we're just creating a User entity class with fields corresponding to the fields of the t_user table.

The sample code is as follows:

         public class User {
         /** number */
         private int id;
         /** Full name */
         private String name; 
         /** Age */
         private int age;
        
         public User(){
         }
         public class User {
         /** number */
         private int id;
         /** Full name */
         private String name; 
         /** Age */
         private int age;
        
         public User(){
         }
        // getter and setter omitted 
        }
       


3.2 Dao Layer Writing

In the previous Dao layer, both hibernate and mybatis could use annotations or mapper profiles.Here we use spring's JPA to do basic add-delete checks.

Explain:

There are two general ways to implement CRUD with a database:
The first is the mapper configuration of the xml.
The second is to use annotations, @Insert, @Select, @Update, @Delete.This article uses the second type.

      

       @Mapper
       public interface UserDao {
       
        /**
        * User data added
        */
        @Insert("insert into t_user(id,name,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(User user);

        /**
        * User data deletion
        */
        @Delete("delete from t_user where id=#{id}")
        void deleteUser(int id);
       
        /**
        * Query user information based on user name
        *
        */
        @Select("SELECT id,name,age FROM t_user where name=#{userName}")
        User findByName(@Param("userName") String userName);
       
        /**
        * Query all
        */
        @Select("SELECT id,name,age FROM t_user") 
        List<User> findAll();
       

       }
      

Explain:

mapper: This annotation is added to the interface to indicate that the interface is a CRUD based on annotations.
Results: Returns a map result set, with property representing the field of the User class and column representing the field of the corresponding database.
Field for Param:sql condition.
Insert, Select, Update, Delete: Add, check, change, delete corresponding 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 */public interface UserService { /** * New User* @param user* @return */ boolean addUser(User user); /** * Modify User* @param user* @return */ boolean updateUser(User user); /** * Delete User* @param id * @return */ boolean deleteUser(int id); /** * Query user information based on user name* @param userName */ User findUserByName(String userName); /** * Query all * @return */ List<User> findAll();}

Implementation Class

@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 List<User> findAll() { 
 return userDao.findAll(); 
 }

}

3.4 Controller Control Layer

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

Explain:
RestController: Methods in the default class are all returned in json format.
RequestMapping: Interface path configuration.
method: Request format.
RequestParam: Request parameters.
The specific implementation is as follows:

@RestController
@RequestMapping(value = "/api/user")
public class UserRestController { 
    @Autowired 
    private UserService userService;

     @RequestMapping(value = "/user", method = RequestMethod.POST) 
     public boolean addUser( User user) { 
         System.out.println("Start adding..."); 
        return userService.addUser(user); 
    }

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

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

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

    @RequestMapping(value = "/userAll", method = RequestMethod.GET) 
    public List<User> findByUserAge() { 
        System.out.println("Start querying all data..."); 
        return userService.findAll(); 
        }
}

3.5 Application Main Program

SpringApplication is the class used to start a Spring application 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 command line parameters as Spring properties.
  3. Refresh the application context and load all the single beans.
  4. Activate all CommandLineRunner beans.

Start the class directly with main, and SpringBoot is automatically configured.

ps: Even now I still think this is really awesome.

Some notes on this class explain:

SpringBootApplication: Turn on component scanning and automatic configuration.
MapperScan: Mappper interface class scan package configuration

The code is as follows:

@SpringBootApplication@MapperScan("com.pancm.dao")
public class Application { public static void main(String[] args) { 
    // Start the embedded Tomcat and initialize the Spring environment and its Spring components         
    SpringApplication.run(Application.class, args); 
    System.out.println("The program is running..."); 
    }
}

4. Code Testing

After writing the code, we test it.

After starting the Application, use the postman tool to test the interface.

The postman tutorial shows you this blog:

http://www.panchengming.com/2...

The test results are as follows:


There is only one get and post test used here, and the actual method has been tested.

Topics: Java Spring SpringBoot Mybatis Database