MyBatis

About MyBatis, most people are familiar with it. MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. MyBatis can configure and map native information using simple XML or annotations to map interfaces and Java’s POJOs(Plain Old Java Objects) to records in the database.

Whether DDD (Domain Driven Design, Domain Driven modeling) or hierarchical architecture style, will involve the operation of the database persistence layer, this article will explain how Spring Boot integration MyBatis to achieve universal Mapper.

Spring Boot integrates MyBatis

Introduction of depend on

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</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>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </dependency>
Copy the code

As can be seen above, Mybatis introduces Mybatis -spring-boot-starter, the starter provided by Mybatis.

Database Configuration

Add the following configuration to application.yml:

spring:
  datasource:
    hikari:
      connection-test-query: SELECT 1
      minimum-idle: 1
      maximum-pool-size: 5
      pool-name: dbcp1
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test? autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=utf-8
    username: user
    password: pwd
    type: com.zaxxer.hikari.HikariDataSource
    schema[0]: classpath:/init.sql
    initialize: true
Copy the code

As you can see, we configured hikari and the basic information for the database. SQL scripts in the CLASSPath are automatically initialized when the application service starts.

CREATE TABLE IF NOT EXISTS `test` (
  `id` bigint(20) unsigned NOT NULL.`local_name` varchar(128) NOT NULL ,
  PRIMARY KEY (`id`))ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy the code

In the SQL script, we create a test table.

After that, we need to configure the path of Mybatis mapping XML file and entity class. Automatically generate code according to mybatis Generator. Including XXMapper. Java, XXEntity. Java, XXMapper. XML. We’ll skip the demo here and jump right into the next step of the generic Mapper implementation.

Use of the universal Mapper

Introduction of depend on

        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>3.4.0</version>
        </dependency>
Copy the code

Abel533, author of universal Mapper, is interested in reading the source code.

Configure the universal Mapper

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import java.util.Properties;

@Configuration
public class MyBatisMapperScannerConfig {
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(a) {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.blueskykong.mybatis.dao");// Scan the DAO in the path
        Properties properties = new Properties();
        properties.setProperty("mappers"."com.blueskykong.mybatis.config.BaseDao");/ / generic dao
        properties.setProperty("notEmpty"."false");
        properties.setProperty("IDENTITY"."MYSQL");
        mapperScannerConfigurer.setProperties(properties);
        returnmapperScannerConfigurer; }}Copy the code

In the configuration, the DAO under the specified path is set and the common DAO is specified. Note that MapperScannerConfigurer comes from the Tk.mybatis. Spring. Mapper package.

BaseDao

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface BaseDao<T> extends Mapper<T>,MySqlMapper<T>{}Copy the code

Universal Mapper interface. Other interfaces inherit this interface.

Create the entity

We need to add the entity corresponding to the test table.

@Data
@Table(name = "test")
@AllArgsConstructor
@NoArgsConstructor
public class TestModel {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String localName;
}
Copy the code

The @table (name = “test”) annotation specifies the database Table name for this entity.

The configuration file

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

To better map Java entities and database fields, we specify the underlined hump mapping configuration.

TestDao write

public interface TestDao extends BaseDao<TestModel> {


    @Insert("insert into test(id, local_name) values(#{id}, #{localName})")
    Integer insertTestModel(TestModel testModel);
}
Copy the code

TestDao inherits from BaseDao and specifies the generic type as the corresponding TestModel. TestDao contains inherited methods such as:

    int deleteByPrimaryKey(Integer userId);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userId);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
Copy the code

You can also customize some methods, and we’ve customized an insertTestModel method above.

Service layer and control layer

This article skip these two layers, relatively simple, readers can refer to the corresponding source address of this article.

results

After we insert a piece of data, we query the corresponding entity. The following log information is displayed on the console:

c.b.mybatis.dao.TestDao.insertTestModel  : ==>  Preparing: insert into test(id, local_name) values(?, ?) 
c.b.mybatis.dao.TestDao.insertTestModel  : ==> Parameters: 5953(Integer), testName(String)
c.b.mybatis.dao.TestDao.insertTestModel  : <==    Updates: 1
c.b.m.dao.TestDao.selectByPrimaryKey     : ==>  Preparing: SELECT id,local_name FROM test WHERE id = ? 
c.b.m.dao.TestDao.selectByPrimaryKey     : ==> Parameters: 5953(Integer)
c.b.m.dao.TestDao.selectByPrimaryKey     : <==      Total: 1
Copy the code

Spring Boot integrated MyBatis to achieve universal Mapper here is done.

summary

MyBatis is a very common component of the persistence layer, and Spring Boot advocates convention over configuration, especially with many XML configurations. Of course, many students use Spring Data. In comparison, I think MyBatis SQL is more flexible than Spring Data, but the specific comparison is not discussed here.

The source address of this article is:

Github.com/keets2012/S…

Subscribe to the latest articles, welcome to follow my official account

reference

  1. abel533/Mapper
  2. Configure Spring Boot to integrate MyBatis, Universal Mapper, Quartz, and PageHelper