Quick Start

Official Website

http://www.mybatis.org/mybatis-3/

Development Steps

  • Add MyBatis coordinates
  • Create User data table
  • Write User entity class
  • Write UserMapper mapping file
  • Write SqlMapConfig.xml core file
  • Write test class

Create Database and Table

Design the database table according to project requirements and write SQL scripts to create the table structure.

Import MyBatis Dependencies

If using Maven to manage the project, add MyBatis dependencies. Common dependencies include MyBatis core library, MyBatis-Spring (if used with Spring), and database driver.

Project Structure Planning

  • Mapper folder: Stores MyBatis mapping interface files
  • Mapper XML folder: Stores MyBatis SQL mapping files
  • Entity class folder: Java entity classes corresponding to database tables
  • Service folder: Encapsulates business logic
  • DAO (or Repository) folder: Encapsulates database operations

Configure mybatis-config.xml

  • Configure database connection information
  • Configure aliases to simplify fully qualified class names of entity classes
  • Specify the path to Mapper XML files

Create Entity Classes

Create Java entity classes corresponding to the database table structure. Property names should match table field names (camelCase naming is recommended).

Write Mapper Interface

Create a Mapper interface to declare methods for database operations. Method names correspond one-to-one with ids in the SQL mapping file. Mapper interfaces don’t need implementation classes; MyBatis generates implementations dynamically.

Write Mapper Mapping Files

Common tags include:

  • select: Query statements
  • insert: Insert statements
  • update: Update statements
  • delete: Delete statements

Dynamic SQL functionality: Use <if>, <where> and other tags to build complex query conditions.

Load Configuration Files

Use SqlSessionFactoryBuilder to read mybatis-config.xml and build SqlSessionFactory. Obtain SqlSession through SqlSessionFactory and execute Mapper methods.


POM

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mybatis-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!--mybatis coordinates-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!--mysql driver coordinates-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
            <scope>runtime</scope>
        </dependency>
        <!--unit test coordinates-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--log coordinates-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
    </dependencies>

</project>

Data Table

CREATE TABLE `user_info` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `money` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

Entity Class

package icu.wzk.model;


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

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo {
    private Long id;
    private String username;
    private String password;
    private Integer age;
}

Mapper

<?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="icu.wzk.mapper.UserInfoMapper">
    <!-- Query single user info -->
    <select id="selectOne" parameterType="java.lang.String" resultType="icu.wzk.model.UserInfo">
        SELECT
            *
        FROM
            user_info
        WHERE
            username = #{username}
    </select>
    <!-- Query all user info -->
    <select id="selectList" resultType="icu.wzk.model.UserInfo">
        SELECT
            *
        FROM
            user_info
    </select>
</mapper>

Core File

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties>
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://172.16.1.130:3306/wzk-mybatis?characterEncoding=utf-8"/>
        <property name="user" value="hive"/>
        <property name="password" value="hive@wzk.icu"/>
    </properties>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driverClass}"/>
                <property name="url" value="${jdbcUrl}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper.xml"/>
    </mappers>
</configuration>

Test Code

package icu.wzk;

import icu.wzk.model.UserInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class WzkIcu01 {
    public static void main(String[] args) throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<UserInfo> dataList = sqlSession.selectList("icu.wzk.mapper.UserInfoMapper.selectList");
        dataList.forEach(System.out::println);
        sqlSession.close();
    }
}

Console Output

24/11/11 15:02:49 DEBUG logging.LogFactory: Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
24/11/11 15:02:49 DEBUG pooled.PooledDataSource: PooledDataSource forcefully closed/removed all connections.
24/11/11 15:02:49 DEBUG jdbc.JdbcTransaction: Opening JDBC Connection
24/11/11 15:02:49 DEBUG jdbc.JdbcTransaction: Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@e50a6f6]
24/11/11 15:02:49 DEBUG UserInfoMapper.selectList: ==>  Preparing: SELECT * FROM user_info
24/11/11 15:02:49 DEBUG UserInfoMapper.selectList: ==> Parameters:
24/11/11 15:02:49 DEBUG UserInfoMapper.selectList: <==      Total: 1
UserInfo(id=1, username=wzk, password=icu, age=18)