Spring boot integrates MyBatis to add, delete, modify and check the complete version of case (with source code)

Keywords: Java Spring Mybatis Maven

1. introduction

Spring Boot is a framework to simplify spring development. It is used to monitor the spring application development. The Convention is larger than the configuration. just run can create an independent, product level application.

When we use Spring boot, we only need to configure the corresponding Spring boot to use all the Spring components. In short, Spring boot integrates many excellent frameworks. We don't need to manually write a bunch of xml configurations and then configure them. In essence, Spring boot is Spring. It does the Spring Bean configuration that you would do without it.
Less gossip, more pictures:

2. start

  • Create a new project
  • Select the Spring Initializr project
  • Create the file structure of the project and the version of jdk. This time, take demo as an example
  • Select the dependencies required for the project
  • Modify the project name, finish, and select modify this time

Take a look at the pom file

<?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 https://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.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</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-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

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

</project>
  • Modify the configuration file. Instead of using the application.properties file, use a more concise application.yml file.

    Change to application.yml
    Content:
server:
  port: 8080

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: com.example.entity.demo

logging:
  level:
    com:
      example:
        mapper : debug

Create table:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

Directory structure:

UserController.java

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

/**
 * @author yn2333
 * @Date 2020/03/03
 */

@RestController
@RequestMapping("/test")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/selectUserByid", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String GetUser(User user){
        return userService.Sel(user).toString();
    }

    @RequestMapping(value = "/add", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String Add(User user){
           return userService.Add(user);
    }

    @RequestMapping(value = "/update", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String Update(User user){
        return userService.Update(user);
    }

    @RequestMapping(value = "/delete", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String Delete(User user){
        return userService.Delete(user);
    }
}

User.java

package com.example.demo.entity;

/**
 * @author yn2333
 * @Date 2020/03/03
 */
public class User {
    private Integer id;
    private String username;
    private String password;
    private String address;

    public User(Integer id, String username, String password, String address) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.address = address;
    }

    public Integer getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getAddress() {
        return address;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

UserMapper.java

package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

/**
 * @author yn2333
 * @Date 2020/03/03
 */
@Repository
public interface UserMapper {

    User Sel(@Param("user")User user);

    int Add(@Param("user")User user);

    int Update(@Param("user")User user);

    int Delete(@Param("user")User user);
}

UserService.java

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yn2333
 * @Date 2020/03/03
 */
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public User Sel(User user) {
        return userMapper.Sel(user);
    }

    public String Add(User user) {
        int a = userMapper.Add(user);
        if (a == 1) {
            return "Add success";
        } else {
            return "Add failure";
        }
    }

    public String Update(User user) {
        int a = userMapper.Update(user);
        if (a == 1) {
            return "Modified success";
        } else {
            return "Modification failed";
        }
    }

    public String Delete(User user) {
        int a = userMapper.Delete(user);
        if (a == 1) {
            return "Delete successful";
        } else {
            return "Delete failed";
        }
    }

}

DemoApplication.java

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * @author yn2333
 * @Date 2020/03/03
 */

@MapperScan("com.example.demo.mapper") //mapper scanned
@SpringBootApplication
public class DemoApplication {

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

}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="com.example.demo.entity.User">
        <result column="id" jdbcType="INTEGER" property="id"/>
        <result column="userName" jdbcType="VARCHAR" property="username"/>
        <result column="passWord" jdbcType="VARCHAR" property="password"/>
        <result column="realName" jdbcType="VARCHAR" property="address"/>
    </resultMap>

    <select id="Sel" resultType="com.example.demo.entity.User">
        select * from user where 1=1
        <if test="user.id != null">
            AND id = #{user.id}
        </if>
    </select>

    <insert id="Add" parameterType="com.example.demo.entity.User">
        INSERT INTO user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="user.username != null">
                username,
            </if>
            <if test="user.password != null">
                password,
            </if>
            <if test="user.address != null">
                address,
            </if>
        </trim>
        <trim prefix="VALUES (" suffix=")" suffixOverrides=",">
            <if test="user.username != null">
                #{user.username,jdbcType=VARCHAR},
            </if>
            <if test="user.password != null">
                #{user.password,jdbcType=VARCHAR},
            </if>
            <if test="user.address != null">
                #{user.address,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>

    <update id="Update" parameterType="com.example.demo.entity.User">
        UPDATE user
        <set>
            <if test="user.username != null">
                username = #{user.username},
            </if>
            <if test="user.password != null">
                password = #{user.password},
            </if>
            <if test="user.address != null">
                address = #{user.address},
            </if>
        </set>
        WHERE
        id=#{user.id}
    </update>

    <delete id="Delete"  parameterType="com.example.demo.entity.User">
        DELETE FROM user WHERE id = #{user.id}
    </delete>

</mapper>

3. test

  • start-up
  • Add to:
    127.0.0.1:8080/test/add?username = infinity & password = 123456 & address = Shanghai
  • Enquiries:
    127.0.0.1:8080/test/selectUserByid?id=1
  • modify
    127.0.0.1:8080 / test / update? Id = 1 & username = code cloud & password = 654321 & address = Beijing
  • delete
    127.0.0.1:8080/test/delete?id=1

    Add, delete, modify and check that the basic test has passed, and the effect can be seen after Navicat is refreshed.
    Source code and sql files are packaged
    Download method 1: https://download.csdn.net/download/weixin_/12223942
    Download method 2:
    Sweep below the two-dimensional code to pay attention to the official account reply: code001 can get

Posted by Shibbey on Wed, 04 Mar 2020 02:41:19 -0800