Springboot + MySQL + CRUD (add, delete, modify and query)

Keywords: Spring MySQL Java SpringBoot

talk is cheap,show you my code
Source code: springboot-mysql-crud

1. Create a springboot project
2. Import related dependencies

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wantao</groupId>
    <artifactId>springboot-mysql-crud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mysql-crud</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Note: I used the lombok plug-in (automatically generate get, set method, etc.), please use Baidu

3. Create a new database (springboot MySQL crud) and a table user(id,username,password)

4. Write the relevant configuration in the configuration file application.properties

#mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3306/springboot-mysql-crud?useSSL=false
spring.datasource.username=root
spring.datasource.password=#Your own database password

#mybatis
mybatis.configuration.map-underscore-to-camel-case=true

#server
server.servlet.context-path=/

5. Create a bean package and create a new User class
Note: I use the lombok plug-in (automatically generate get, set method, etc.), if not, please generate get, set method by yourself or Baidu

package com.wantao.springbootmysqlcrud.bean;

import lombok.Data;
@Data
public class User {
    private Integer id;
    private String username;
    private String password;
}

6. Create dao package and create CRUDDao to write corresponding sql statement by annotation

package com.wantao.springbootmysqlcrud.dao;

import com.wantao.springbootmysqlcrud.bean.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Mapper
public interface CRUDDao {
     @Select("select * from user")
     List<User> getAllUser();
     @Select("select * from user where id =#{id}")
     User getUserById(@Param("id") Integer id);
     @Insert("insert into user(id,username,password) values(#{id},#{username},#{password})")
     int addUser(User user);
     @Update("update user set username=#{username},password=#{password} where id=#{id}")
     int updateUser(User user);
     @Delete("delete from user where id=#{id}")
     int deleteUser(@Param("id") Integer id);
}


7. Create a service package, create a new CRUDService class, and implement the CRUDDao interface

package com.wantao.springbootmysqlcrud.CRUDService;

import com.wantao.springbootmysqlcrud.bean.User;
import com.wantao.springbootmysqlcrud.dao.CRUDDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CRUDService implements CRUDDao {
    @Autowired
    private CRUDDao crudDao;
    @Override
    public List getAllUser() {
        return crudDao.getAllUser();
    }

    @Override
    public User getUserById(Integer id) {
        return crudDao.getUserById(id);
    }

    @Override
    public int addUser(User user) {
        return crudDao.addUser(user);
    }

    @Override
    public int updateUser(User user) {
        return crudDao.updateUser(user);
    }

    @Override
    public int deleteUser(Integer id) {
        return crudDao.deleteUser(id);
    }
}

8. For better data display, create a result package and a new result class (used to encapsulate the returned json)

package com.wantao.springbootmysqlcrud.result;

import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * Json data encapsulation returned
 */
@Data
@NoArgsConstructor
public class Result{
    private Integer code;
    private String msg;
    private Map<String, Object> data = new HashMap<String, Object>();

    /**
     * Called on success
     * Default status code: 200
     */
    public static Result success() {
        Result result = new Result();
        result.setCode(200);
        result.setMsg("Successful treatment");
        return result;
    }

    /**
     * Call on failure
     * Default status code: 500
     */
    public static Result error() {
        Result result = new Result();
        result.setCode(500);
        result.setMsg("Processing failure");
        return result;
    }

    /**
     * Setting data
     * @param key
     * @param value
     * @return
     */
    public Result add(String key,Object value){
        this.data.put(key,value);
        return this;
    }

}

9. Create controller package and create CRUDController class

package com.wantao.springbootmysqlcrud.controller;

import com.wantao.springbootmysqlcrud.CRUDService.CRUDService;
import com.wantao.springbootmysqlcrud.bean.User;
import com.wantao.springbootmysqlcrud.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class CRUDController {
    @Autowired
    private CRUDService crudService;

    /**
     * Query a user
     * @param id
     * @return
     */
    @GetMapping("/getUserById/{id}")
    public Result getUserById(@PathVariable("id")Integer id){
        User user=crudService.getUserById(id);
        return Result.success().add("user",user);
    }

    /**
     * Query all users
     * @return
     */
    @GetMapping("/getAllUser")
    public Result getAllUser(){
        List<User> users=crudService.getAllUser();
        return Result.success().add("user",users);
    }

    @GetMapping("/addUser")
    public Result addUser(){
        User user=new User();
        user.setId(2);
        user.setUsername("selenium1");
        user.setPassword("123");
        crudService.addUser(user);
        return Result.success();
    }

    @GetMapping("/updateUser")
    public Result updateUser(){
        User user=new User();
        user.setId(1);
        user.setUsername("seleniumupdate");
        user.setPassword("123");
        crudService.updateUser(user);
        return Result.success();
    }

    @GetMapping("/deleteUser/{id}")
    public Result deleteUser(@PathVariable("id") Integer id){
        crudService.deleteUser(id);
        return Result.success();
    }



}


That's it

Now let's put the result chart

1. Query a user

2. Add a new user (query all users and you can see that we have added it)

3. Query all users

4. Modify the user (you can see that user 1 has been modified)

5. Delete user (it can be seen that user 2 has been deleted)

Source code: springboot-mysql-crud

Posted by Chris 96 WS6 on Tue, 05 Nov 2019 08:01:46 -0800