Setting Up TkMyBatis in Spring Boot Applications
Maven Dependency
Add the following dependency to your pom.xml file:
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
Defining Mapper Interfaces
Create mapper interfaces in your DAO layer that extend tk.mybatis.mapper.common.Mapper. The generic type parameter represents your entity class.
package com.example.tkmybatis.mapper;
import com.example.tkmybatis.entity.Department;
import tk.mybatis.mapper.common.Mapper;
public interface DepartmentMapper extends Mapper<Department> {
}
Configuring Mapper Scanning
Add the @MapperScan annotation to your main application class to enable Spring to discover your mapper interfaces:
package com.example.tkmybatis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.example.tkmybatis.mapper")
public class TkMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(TkMybatisApplication.class, args);
}
}
DataSource Configuration
Configure your database connection in application.yml:
server:
servlet:
context-path: /mapper
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password:
logging:
level:
org.example: debug
Entity Class Definition
Define your entity using JPA annotations for mapping to database tables:
import javax.persistence.Table;
import lombok.Data;
/**
* Mapping entity to database table using JPA conventions
*/
@Data
@Table(name = "t_user")
public class User {
@Id
@Column(name = "user_id")
private Integer userId;
@Column(name = "user_name")
private String userName;
@Column(name = "password")
private String password;
}
Writing Test Cases
Create integration tests to verify mapper functionality:
package com.example.tkmybatis;
import com.example.tkmybatis.entity.User;
import com.example.tkmybatis.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void findOne() {
User user = userMapper.selectByPrimaryKey(1);
System.out.println(user);
}
}
Automatic Code Generation
Project Strucutre
Maven Plugin Configuration
Add the MyBatis Generator plugin to your pom.xml:
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<configurationFile>
${basedir}/src/main/resources/generator/generatorConfig.xml
</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
</plugin>
Generator Configuration Files
Create two configuration files in src/main/resources/generator/: config.properties and generatorConfig.xml.
config.properties:
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?nullCatalogMeansCurrent=true&serverTimezone=GMT%2b8
jdbc.user=root
jdbc.password=
moduleName=dept
tableName=t_dept
generatorConfig.xml:
<generatorConfiguration>
<properties resource="generator/config.properties"/>
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
<property name="caseSensitive" value="true"/>
<property name="lombok" value="Getter,Setter,ToString"/>
</plugin>
<jdbcConnection driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.url}"
userId="${jdbc.user}"
password="${jdbc.password}">
</jdbcConnection>
<javaModelGenerator targetPackage="com.example.tkmybatis.entity.${moduleName}"
targetProject="src/main/java"/>
<sqlMapGenerator targetPackage="com.example.tkmybatis.mapper.${moduleName}"
targetProject="src/main/java"/>
<javaClientGenerator targetPackage="com.example.tkmybatis.mapper.${moduleName}"
targetProject="src/main/java"
type="XMLMAPPER"/>
<table tableName="${tableName}">
<generatedKey column="id" sqlStatement="JDBC"/>
<domainObjectRenamingRule searchString="^T" replaceString=""/>
</table>
</context>
</generatorConfiguration>
Running the Generator
Execute the code generator through Maven:
- Open the Maven tool window in your IDE
- Locate the newly added plugin configuration
- Double-click the
mybatis-generator:generategoal
This generates the mapper interfaces, XML mapping files, and entity classes for the configured table.