Welcome to my GitHub

Github.com/zq2599/blog…

Content: all original article classification summary and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.;

MyBatis primary combat

MyBatis primary combat series aims to master the basic usage of MyBatis with readers through a series of coding combat, and help beginners to quickly use MyBatis to participate in the actual development;

Focus on MyBatis

“MyBatis Primary Combat” is for readers who are interested in MyBatis, to provide readers with available solutions and codes, here is not a comparison of Hibernate, SQLtoy-ORM, the author is also very recognized these ORM framework, but “MyBatis primary Combat” does not participate in the comparison;

About MyBatis

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all of the JDBC code and the work of setting parameters and fetching result sets. MyBatis can configure and map primitive types, interfaces, and Java POJOs (Plain Old Java Objects) to records in the database via simple XML or annotations.

Actual combat environment

The environmental information of MyBatis Primary Combat series is as follows:

  1. The JDK: 1.8.0 comes with _181
  2. Mybatis -spring-boot-starter: 2.1.3 (mybatis: 3.5.5)
  3. Spring the Boot: 2.3.2. RELEASE
  4. MySQL: 5.7.29
  5. Actual combat environment: WIN10
  6. Development tools: IntelliJ IDEA 2019.2.1 (Ultimate Edition)

Overview of general steps for Spring Boot integration with MyBatis

The general steps for Spring Boot to integrate MyBatis are as follows:

  1. Add mybatis-spring-boot-starter dependency to Maven;
  2. Spring Boot configuration specifies the location of the MyBatis configuration file.
  3. Spring Boot configuration specifies the MyBatis mapping file location;
  4. Add MyBatis configuration file, the subsequent general configuration of MyBatis is concentrated here;
  5. Mapping file xxxmapper. XML and its corresponding interface file;
  6. In business code, Autowired annotations decorate the interface file and use them;
  • Next, let’s get the data ready.

To prepare data

  1. Please prepare MySQL service by yourself. My MySQL is deployed on docker. You can refer to “Qunhui DS218+ MySQL Deployment”.
  2. Create a database named Mybatis
  3. Execute the following SQL in mybatis database to create the required data for this actual combat:
USE mybatis;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `age` int(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;


DROP TABLE IF EXISTS `log`;

CREATE TABLE `log` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `user_id` int(32),
  `action` varchar(255) NOT NULL,
  `create_time` datetime not null,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO mybatis.user (id, name, age) VALUES (3, 'tom', 11);
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (3, 3, 'read book', '2020-08-07 08:18:16');
Copy the code

Download the source code

  1. If you don’t want to code, you can download all the source code at GitHub, with the address and link information listed in the following table (github.com/zq2599/blog…
The name of the link note
Project home page Github.com/zq2599/blog… The project’s home page on GitHub
Git repository address (HTTPS) Github.com/zq2599/blog… The project source warehouse address, HTTPS protocol
Git repository address (SSH) [email protected]:zq2599/blog_demos.git The project source warehouse address, SSH protocol
  1. This Git project has multiple folders. The application of this chapter is in the Mybatis folder, as shown in the red box below:

About Parent-child Project

In order to manage the whole series of code, I use Maven to create a parent-child project. If you only need a sub-project and do not need a parent-child structure, you need to make the following adjustments to the sub-project pom.xml:

  1. The parent node originally looks like this:
<parent>
        <groupId>com.bolingcavalry</groupId>
        <artifactId>mybatis</artifactId>
        <version>1.0 the SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
Copy the code

Replace it with the following: spring-boot-starter-parent

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2. RELEASE</version>
        <relativePath/> <! -- lookup parent from repository -->
    </parent>
Copy the code
  1. There is no version child node in the dependency node of the child project. These are managed in the dependencyManagement of the parent project. Please add version to each dependency node of the child project:

  • So let’s start coding

Create parent project

Create maven project named Mybatis.


      
<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.3.2. RELEASE</version>
        <relativePath/> <! -- lookup parent from repository -->
    </parent>

    <groupId>com.bolingcavalry</groupId>
    <artifactId>mybatis</artifactId>
    <version>1.0 the SNAPSHOT</version>
    <packaging>pom</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <modules>
        <module>simple</module>
    </modules>

    <dependencyManagement>

        <dependencies>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.3</version>
            </dependency>
        </dependencies>

    </dependencyManagement>

</project>
Copy the code
  • At this point, the preparation work is complete, let’s start to create a typical Spring Boot integration MyBatis project;

Spring Boot integrates MyBatis

  1. Create a Spring Boot child project named simple under the parent project mybatis and its pom.xml content is as follows:

      
<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>com.bolingcavalry</groupId>
        <artifactId>mybatis</artifactId>
        <version>1.0 the SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>com.bolingcavalry</groupId>
    <artifactId>simple</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
    <name>simple</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-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</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>
Copy the code
  1. Spring the Boot configuration file is a simple/SRC/main/resources/application. The yml, content is as follows:
server:
  port: 8080

spring:
  # data source
  datasource:
    username: root
    password: 123456
    url: JDBC: mysql: / / 192.168.50.43:3306 / mybatis? useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

# mybatis configuration
mybatis:
  # Config file location
  config-location: classpath:mybatis-config.xml
  # Map file location
  mapper-locations: classpath:mappers/*Mapper.xml

# log configuration
logging:
  level:
    root: INFO
    com:
      bolingcavalry:
        simple:
          mapper: debug
Copy the code
  1. Create entity class user.java for user;
package com.bolingcavalry.simple.entity;

/ * * *@Description: entity class *@author: willzhao E-mail: [email protected]
 * @date: 2020/8/4 24 * /
public class User {
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId(a) {
        return id;
    }

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

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge(a) {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString(a) {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\' ' +
                ", age=" + age +
                '} '; }}Copy the code
  1. Create log.java (log.java);
package com.bolingcavalry.simple.entity;

import java.sql.Date;

/ * * *@Description: entity class *@author: willzhao E-mail: [email protected]
 * @date: 2020/8/4 24 * /
public class Log {
    private Integer id;
    private Integer userId;
    private String action;
    private Date createTime;

    public Integer getId(a) {
        return id;
    }

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

    public Integer getUserId(a) {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getAction(a) {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public Date getCreateTime(a) {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString(a) {
        return "Log{" +
                "id=" + id +
                ", userId=" + userId +
                ", action='" + action + '\' ' +
                ", createTime=" + createTime +
                '} '; }}Copy the code
  1. Next, we will create three new configuration files. Let’s take a look at their locations to avoid unnecessary trouble:

6. In the application. Yml directory, add the mybatis-config. XML file, which is the mybatis configuration file.

<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <! Classes in mapping files do not need to write full path
        <package name="com.bolingcavalry.simple.entity"/>
    </typeAliases>
</configuration>
Copy the code
  1. Mysql > add a file named usermapper. XML under resources/mappers, where usermapper. XML can be used to query the user table. TypeAliases package node is configured in mybatis-config. XML file.

      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bolingcavalry.simple.mapper.UserMapper">
    <select id="sel" parameterType="int" resultType="User">
        select * from user where id = #{id}
    </select>
</mapper>
Copy the code
  1. Log. Java does not have the same name as the user_id field in the log table. Therefore, we need to add a resultMap to establish the field mapping relationship between the database and the entity class, and then use this relationship in the select node. Note that the resultMap attribute is used (usermapper. XML uses a resultType) :

      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bolingcavalry.simple.mapper.LogMapper">

    <resultMap id="logResultMap" type="Log">
        <id property="id" column="id" />
        <result column="user_id" jdbcType="INTEGER" property="userId" />
        <result column="action" jdbcType="VARCHAR" property="action" />
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
    </resultMap>

    <select id="sel" parameterType="int" resultMap="logResultMap">
        select * from log where id = #{id}
    </select>
</mapper>
Copy the code
  1. Next are the interface files used by the business. The first one is usermapper.java:
package com.bolingcavalry.simple.mapper;

import com.bolingcavalry.simple.entity.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper {
    User sel(int id);
}
Copy the code
  1. The second is logmapper.java:
package com.bolingcavalry.simple.mapper;

import com.bolingcavalry.simple.entity.Log;
import org.springframework.stereotype.Repository;

@Repository
public interface LogMapper {
    Log sel(int id);
}
Copy the code
  1. Both classes use the Repository annotation to avoid red lines in IDEA during coding, as shown below:

Java class userService. Java, which uses the Autowired annotation to inject the implementation of UserMapper:

package com.bolingcavalry.simple.service;

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

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public User sel(int id){
        returnuserMapper.sel(id); }}Copy the code
  1. Logservice.java = logservice.java
package com.bolingcavalry.simple.service;

import com.bolingcavalry.simple.entity.Log;
import com.bolingcavalry.simple.mapper.LogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LogService {
    @Autowired
    LogMapper logMapper;

    public Log sel(int id){
        returnlogMapper.sel(id); }}Copy the code
  1. Finally, there are the Controller classes that respond to Web requests, the first of which is userController.java:
package com.bolingcavalry.simple.controller;

import com.bolingcavalry.simple.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("user/{id}")
    public String GetUser(@PathVariable int id){
        returnuserService.sel(id).toString(); }}Copy the code
  1. Then logController.java:
package com.bolingcavalry.simple.controller;

import com.bolingcavalry.simple.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LogController {
    @Autowired
    private LogService logService;

    @RequestMapping("log/{id}")
    public String log(@PathVariable int id){
        returnlogService.sel(id).toString(); }}Copy the code
  1. The MapperScan annotation will automatically scan all interfaces in the package path, so that UserMapper and LogMapper don’t need Mapper annotation:
package com.bolingcavalry.simple;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.bolingcavalry.simple.mapper")
public class SimpleApplication {

    public static void main(String[] args) { SpringApplication.run(SimpleApplication.class, args); }}Copy the code
  • At this point, the coding is complete and you can start validation;

validation

  1. There are two ways to start the SpringBoot application. The easiest way is to directly start the SpringBoot application in IDEA, as shown in the following figure:

  1. MVN clean package -u in the simple directory will result in the simple 0.0.1- snapshot.jar file in the target directory. Then run Java -jar simple-0.0.1 -snapshot. jar to start.
  2. In the browser to http://localhost:8080/user/3, you can get the user table query result:

4. Visithttp://localhost:8080/log/3, the query result of log table can be obtained:

5. On the console, you can see the log below, which is an important clue to debugging problems during our development:

At this point, the entry-level SpringBoot integration of MyBatis combat is completed, the next series of content will have more combat, let’s learn and master the basic use of MyBatis;

You are not alone, Xinchen original accompany all the way

  1. Java series
  2. Spring series
  3. The Docker series
  4. Kubernetes series
  5. Database + middleware series
  6. The conversation series

Welcome to pay attention to the public number: programmer Xin Chen

Wechat search “programmer Xin Chen”, I am Xin Chen, looking forward to enjoying the Java world with you…

Github.com/zq2599/blog…