Integrated Mybatis Framework for SpringBoot Basic Learning

Posted by exa_bit on Tue, 19 Oct 2021 18:23:02 +0200

Preface:

Hello, ladies and gentlemen, I'm running like a snail rz. Of course you can call me Snail Jun. I'm a beginner who has studied Java for more than half a year. At the same time, I have a great dream that I will become an excellent Java architect one day.
This SpringBoot Basic Learning Series is used to record the entire process of learning the basic knowledge of the SpringBoot framework (this series was written with reference to the latest SpringBoot tutorial from Station B, which was sorted out before but was not published at that time, so there may be errors in some places, I hope you can correct them in time!)
Later, I will update this series at a faster rate each day, and those who haven't studied SpringBoot can refer to my blog to learn about it. Of course, the little buddy who has studied can also review the basics with me by the way.
Finally, I hope I can make progress with you! Come on! Boys!

Say nothing more, let's start today's learning, because today we're at the eighth stop of SpringBoot Basic Learning: Integrating Mybatis Framework!

6.3 Integrating Mybatis Framework

6.3.1 Set up the basic environment of the project

1. Create a Spring Boot project

  • Create Spring Initializr Project

  • Set up basic project information, set up Group, Artifact, Java Vesrion, etc.

  • Introduce project resource dependency, Spring Web, JDBC API, MySQL Driver, etc.

  • Select project storage location

  • New Project Succeeded

  • Delete redundant files, project structure as follows

2. Introducing Mybatis and Lombok resource dependency

  • Introducing MyBatis resource dependency,
 <!-- Starter provided by third party -->
 <!-- Mybatis-SpringBoot Launcher -->
 <!-- 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.1.3</version>
 </dependency>
  • Introducing Lombok resource dependency
<!-- lombok resources dependence -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.10</version>
</dependency>
  • pom.xml file after introducing related resource 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 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.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.kuang</groupId>
    <artifactId>springboot-05-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-05-mybatis</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        
        <!-- Spring Official Launcher -->  
        <!-- Spring Boot Of JDBC starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- Spring Boot Of Web starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- SpringBoot Test Launcher -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- MySQL Database Driven Resource Dependency -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.46</version>
        </dependency>
        
        <!-- Starter provided by third party -->
        <!-- Mybatis-SpringBoot Launcher -->
        <!-- 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.1.3</version>
        </dependency>
        <!-- lombok resources dependence -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
    </dependencies>

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

</project>
  • View project resource dependencies

3. Connect to MySQL database

3-1 Write the core configuration file for the applicationContext
  • Write configuration files in properties format
# Configure database related properties
# Database user login
spring.datasource.username=root
# Database login password
spring.datasource.password=123456
# Database url connection
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true
# Database Driver Name
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# Configure Tomcat server port number
server.port=8888
  • Write a configuration file in yml format
# Set up database drivers
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true
    # com.mysql.jdbc.Driver is a database under version 8.0
    driver-class-name: com.mysql.jdbc.Driver
# Set Server Port Number
server:
  port: 8888
3-2 Connect to MySQL Database
  • Add data source, select MySQL database

  • Set database login user name and password for test connection

  • Select the specific database to connect to

  • Successful connection, database table on right

3-3 Database Connection Failure Solution

Encountered during test connection:

Solution: Set time zone for MySQL database

1. Connect mysql
mysql  -u root -p

2. View the system default time zone
show variables like'%time_zone';

3. Set a new time zone
set global time_zone = '+8:00'; 
4. View the modified time zone

Note that you need to exit the command window and reenter to see the modified time zone

show variables like'%time_zone';

4. View default data sources and connections

  • Modify Springboot's test class
package com.kuang;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootTest
class Springboot05MybatisApplicationTests {

    //Automatically assemble DataSource data sources into Spring containers
    @Autowired
    private DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        //Print class information for data sources
        System.out.println(dataSource.getClass());
        //Print data source connection information
        System.out.println(dataSource.getConnection());
    }

}
  • View default data sources and connections

6.3.2 Perfecting the Basic Environment of Project

1. Project infrastructure and modification of configuration files

1-1 Project Basic Structure

1-2 Modify Core Profile
# Configure database related properties
# Database user login
spring.datasource.username=root
# Database login password
spring.datasource.password=123456
# Database url connection
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true
# Database Driver Name
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# Configure Tomcat server port number
server.port=8888

# Configuring mybatis-related properties
# Setting aliases through packages
mybatis.type-aliases-package=com.kuang.pojo
# Set the location of mapper map file
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
# Don't precede mybatis/mapper/*.xml with /, otherwise you'll start looking in the project root directory
# mybatis.mapper-locations=classpath:/mybatis/mapper/*.xml

2. Write User entity classes and UserMapper interfaces

2-1 Writing User Entity Classes
package com.kuang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data // Introduce parameterless constructs, get and set methods, and toString methods
@AllArgsConstructor // Introducing a parametric construction
@NoArgsConstructor // Re-introduce parametric construction to prevent parametric construction from being overwritten when parametric construction is introduced
// User Entity Class
public class User {
    
    private Integer id;
    private String name;
    private String pwd;
    
}
2-2 Write UserMapper interface
package com.kuang.mapper;

import com.kuang.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;

// Use the @Mapper annotation to indicate that the interface is a Mapper class for Mybatis
@Mapper
// Delegate the Dao interface to Spring management using the @Repository annotation
@Repository
public interface UserMapper {
    
    // Get all user information
    public List<User> getUserList();
    
    // Get specified user information via Id
    public User getUserById(int id);
    
    // Add user information
    public int addUser(User user) ;
    
    // Delete user information
    public int deleteUser(int id);
    
    // Modify user information
    public int updateUser(User user);
    
}
2-3 Write UserMapper.xml file
<?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.kuang.mapper.UserMapper">

    <!-- Get all user information -->
    <!-- resultType Represents the return value type, getUserList Method return value is User object -->
    <select id="getUserList" resultType="com.kuang.pojo.User">
       Select * from mybatis.user
    </select>

    <!-- adopt Id Get specified user information -->
    <!-- resultType Represents the return value type, getUserById Method return value is User object
         parameterType Represents the parameter type, which by default is int Type, so this property can be set without -->
    <select id="getUserById" resultType="com.kuang.pojo.User"  parameterType="int">
       Select * from mybatis.user where id = #{id}
    </select>

    <!-- Increase user information -->
    <!-- parameterType Represents the parameter type, addUser The parameter type of the method is User -->
    <insert id="addUser" parameterType="User">
        Insert into mybatis.user(id, name, pwd)
        values (#{id}, #{name}, #{pwd})
    </insert>

    <!-- Delete user information-->
    <!-- parameterType Represents the parameter type, deleteUser The parameter type of the method is int -->
    <delete id="deleteUser" parameterType="int">
        Delete from mybatis.user where id = #{id}
    </delete>

    <!-- Modify user information -->
    <!-- parameterType Represents the parameter type, updateUser The parameter type of the method is User -->
    <update id="updateUser" parameterType="User">
        Update mybatis.user set name=#{name}, pwd=#{pwd}
        where id = #{id}
    </update>

</mapper>

3. Write UserMapper mapping file and UserController controller

3-1 Write UserMapper.xml mapping file
<?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.kuang.mapper.UserMapper">

    <!-- Get all user information -->
    <!-- resultType Represents the return value type, getUserList Method return value is User object -->
    <select id="getUserList" resultType="com.kuang.pojo.User">
       Select * from mybatis.user
    </select>

    <!-- adopt Id Get specified user information -->
    <!-- resultType Represents the return value type, getUserById Method return value is User object
         parameterType Represents the parameter type, which by default is int Type, so this property can be set without -->
    <select id="getUserById" resultType="com.kuang.pojo.User"  parameterType="int">
       Select * from mybatis.user where id = #{id}
    </select>

    <!-- Increase user information -->
    <!-- parameterType Represents the parameter type, addUser The parameter type of the method is User -->
    <insert id="addUser" parameterType="User">
        Insert into mybatis.user(id, name, pwd)
        values (#{id}, #{name}, #{pwd})
    </insert>

    <!-- Delete user information -->
    <!-- parameterType Represents the parameter type, deleteUser The parameter type of the method is int -->
    <delete id="deleteUser" parameterType="int">
        Delete from mybatis.user where id = #{id}
    </delete>

    <!-- Modify user information -->
    <!-- parameterType Represents the parameter type, updateUser The parameter type of the method is User -->
    <update id="updateUser" parameterType="User">
        Update mybatis.user set name=#{name}, pwd=#{pwd}
        where id = #{id}
    </update>

</mapper>
3-2 Write UserController controller class
package com.kuang.controller;

import com.kuang.mapper.UserMapper;
import com.kuang.pojo.User;
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.HashMap;
import java.util.List;
import java.util.Map;

// Implement the Controller interface using the @RestController annotation and return the result as a string
@RestController
public class UserController {

    // Automatically assemble userMapper into Spring container using @Autowired annotation
    @Autowired
    private UserMapper userMapper;

    // Query all user information
    /** 
     * True access path: http://localhost:8080/getList
     * Set the request mapping path using the @GetMapping annotation
     * You can also use the @RequestMapping annotation, both of which are request by get
     */
//    @RequestMapping("/getList")
    @GetMapping("/getList")
    public List<User> getUserList() {
        //Call the Dao layer's getUserList method to get a list of all user information
        List<User> users = userMapper.getUserList();
        //Traverse the user information list
        for (User user : users) {
            //Print user information
            System.out.println(user);
        }
        //Return to user information list
        return users;
    }
    
    /**
     * Specify user information by Id query (not recommended by specifying user Id ahead of time)
     */   
    /**
     * True access path: http://localhost:8080/getUser
     * Set the request mapping path using the @GetMapping annotation
     */
    @GetMapping("/getUser2")
    public User getUserById() {
        // Call the Dao layer's getUserById method to obtain the specified user information via Id
        User user = userMapper.getUserById(1);
        // Print specified user information
        System.out.println(user);
        // Return user object
        return user;
    }

    /**
     * Specify user information through Id queries (in general style)
     */
    /**
     * True access path: http://localhost:8080/getUser/?id=1
     * Set the request mapping path using the @GetMapping annotation
     */
    @GetMapping("/getUser")
    public User getUserById2(int id) {
        // Call the Dao layer's getUserById method to obtain the specified user information via Id
        User user = userMapper.getUserById(id);
        // Print specified user information
        System.out.println(user);
        // Return user object
        return user;
    }

    /** 
     * Specify user information by Id query
     * With the restful style, this is recommended
     */
    /**
     * True access path: http://localhost:8080/getUser/1
     * Using the @GetMapping annotation, set the request mapping path: using the restful style
     */
    @GetMapping("/getUser/{userId}")
    // Use the @PathVariable annotation: make the method value correspond to the URL template variable
    public User getUserById3(@PathVariable("userId") int id) {
        // Call the Dao layer's getUserById method to obtain the specified user information via Id
        User user = userMapper.getUserById(id);
        // Print specified user information
        System.out.println(user);
        // Return user object
        return user;
    }

    // Increase user information
    /**
     * True access path: http://localhost:8080/addUser
     * Set the request mapping path using the @GetMapping annotation
     */
    @GetMapping("/addUser")
    public String addUser() {
         // Get user object
         User user = new User();
         // Set User Information
         user.setId(6);
         user.setName("Zhang Bichen");
         user.setPwd("zbc123456");
        // Call the Dao layer's addUser2 method to add user information
         userMapper.addUser(user);
        // Returns the successfully added string
        return "addUser-OK";
    }

    // Delete user information via Id
    /**
     * True access path: http://localhost:8080/deleteUser/2
     * Using the @GetMapping annotation, set the request mapping path: using the restful style
     */
    // Bind method variables to URL templates using the @PathVariable annotation
    @GetMapping("/deleteUser/{userId}")
    public String deleteUser(@PathVariable("userId") int id) {
        userMapper.deleteUser(id);
        return "deleteUser-OK";
    }

    // Modify user information
    /**
     * True access path: http://localhost:8080/updateUser/2
     * Using the @GetMapping annotation, set the request mapping path: using the restful style
     */
    @GetMapping("/updateUser/{userId}")
    // Bind method variables to URL templates using the @PathVariable annotation
    public String updateUser(@PathVariable("userId") int id) {
        // Get user object
        User user = new User();
        // Set User Information
        user.setName("Xue Zhiqian");
        user.setPwd("xzq123456");
        user.setId(id);
        // Call the Dao layer updateUser2 method to modify user information
        userMapper.updateUser(user);
        // Return modified success string
        return "updateUser-OK";
    }

}

4. Add or delete checks and test results

4-1 Query all user information
  • Page Request

  • console output

4-2 Specify user information by Id query
  • Page Request

    Use the general style:

    Use RestFul style:

  • console output

4-3 Increase user information
  • Page Request

  • database information

4-4 Delete user information
  • Page Request

  • database information

4-5 Modify user information
  • Page Request

  • database information

Okay, that's the end of today's study on the integration of Mybatis framework for SpringBoot basic learning. We welcome your friends to actively study and discuss. If you like, you can give Snail Monkey some attention. By the way, I'll see you next time. Bye!

Reference video link: https://www.bilibili.com/video/BV1PE411i7CV([Crazy Java] SpringBoot's latest tutorial IDEA version is easy to understand)

Topics: Java MySQL Mybatis Spring Boot IDEA