1. Introduction

Today we continue to build the scaffolding of KonO Spring Boot. The last article integrates some basic functions, such as unified return body, unified exception handling, fast type conversion, parameter verification and other common necessary functions, and writes some unit tests for verification. Today, Mybatis, the most popular ORM framework in China, is also integrated into it. The Spring Boot version used is 2.3.2.release.

Gitee: gitee.com/felord/kono 1.0.0.MYBATIS branch

Making: github.com/NotFound403… 1.0.0. MYBATIS branch

2. Steps for integrating Mybatis

The steps for integrating Mybatis are not particularly complicated. I have divided them into three steps and then I will get down to business.

3. Dependency integration

Starter of Mybatis add to Kono-dependencies and add to kono-app

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
Copy the code

From the Maven plugin of IDEA, we can see that after introducing Mybatis Starter, the high performance data source connection pool is integrated. The database driver needs to be introduced by ourselves. Here we directly refer to MySQL’s dependencies:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
Copy the code

4. Configuration

Configuration is the most important part, so let’s go through configuration level by level.

4.1 Configure the data source first

The datasource configuration prefix in application.yml is spring.datasource. The basic configuration is as follows:

spring:
  datasource:
    The qualified name of the connection pool implementation, where hikari connection pools are used. You don't need to configure this. It is automatically loaded in the classpath. This is an optional configuration.
    # type: com.zaxxer.hikari.HikariDataSource
    The fully qualified class name of the JDBC driver, which is actually automatically detected based on the following URL configuration, which is optional.
    # driver-class-name: com.mysql.cj.jdbc.Driver
    # JDBC link for database
    url: jdbc:mysql://ip:port/database
    Database user name
    username:
    # database password
    password:
Copy the code

The hikari connection pool can be configured using spring.datasource.hikari as required. The default connection pool is used and can be modified later if necessary.

Com.mysql.jdbc.driver has been marked as obsolete, please use com.mysql.cj.jdbc.driver now.

4.2 mybatis configuration

Mybatis basic configuration is not particularly much, you just need to let Mybatis know from where to load your definition of Mapper interface, from where to load the corresponding * mapper. XML file, and then configure some mybatis features, complex operations can be from my previous Mybatis related articles to see.

I create a new table user_Info, create the corresponding entity class UserInfo, and then define the location of the Mapper interface. If I put all Mapper interfaces in cn.felord.kono. Mapper, then I should use @mapperscan to identify the path and direct Mybatis to find these Mapper interfaces.

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

/**
 * mybatis configuration.
 *
 * @author felord.cn
 */
@MapperScan("cn.felord.kono.mapper")
@Configuration
public class MybatisConfiguration {}Copy the code

Next we write the UserInfoMapper interface corresponding to UserInfo and add a new method. Here you can download some Mybatis plug-ins to facilitate our development according to IDE to the plug-in market. You can search mybatis by keyword. Here I randomly find a plug-in to install. ALT+ENTER shortcut key of IDEA brings up a menu to generate XML corresponding to UserInfoMapper. We can use it to generate XML files and statements corresponding to methods.

The location of the XML file is stored in the mapper folder under Resources. After compiling, the mapper folder under the classpath should be configured as follows in application.yml.

mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
Copy the code

The corresponding userinfomapper. XML file:


      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.felord.kono.mapper.UserInfoMapper">
    <insert id="save" parameterType="cn.felord.kono.entity.UserInfo">
        insert into user_info (name, age)
        VALUES (#{name}, #{age})
    </insert>
</mapper>
Copy the code

Then test that the addition succeeded without any problems, but the unit test of the query failed:

@Test
void testUserInfoMapperFindById(a){

    UserInfo userInfo = userInfoMapper.findById(3);

    System.out.println("userInfo = " + userInfo);
    Assertions.assertEquals(3,userInfo.getUserId());

}
Copy the code

The user_id cannot be injected into the userId, so declare the following configuration to support underline to camel:

mybatis:
  configuration:
      map-underscore-to-camel-case: true
Copy the code

How do I print SQL statements? You only need to set the log level of the Mapper interface package to DEBUG.

logging:
  level:
    cn.felord.kono.mapper: debug
Copy the code

5. To summarize

At this point the basic MyBatis integration is complete, you can pull down from the project repository, configure a database to run. Pay more attention: The yard farmer Pangu continues to come and work with me to assemble the scaffolding. Follow our public id: Felordcn for more information

Personal blog: https://felord.cn