MyBatis Installation and Getting Started

📢 This article was translated by gemini-3-flash-preview

MyBatis Series

MyBatis Installation and Getting Started: This article
MyBatis Usage: https://blog.yexca.net/en/archives/216

MyBatis is a top-tier persistence framework designed to simplify JDBC development.

Installing MySQL on Windows

Download: https://dev.mysql.com/downloads/mysql/

Download the ZIP Archive.

Unzip it, then configure the environment variable MYSQL_HOME and add %MYSQL_HOME%\bin to your PATH.

Open CMD with Administrator privileges and type mysql to verify the configuration.

Initialize MySQL

Run the following command:

1
mysqld --initialize-insecure

Wait a moment; a data folder will be generated in the MySQL directory.

Register MySQL Service

Command:

1
mysqld -install

Start MySQL Service

Commands:

1
2
3
4
# Start MySQL service
net start mysql
# Stop MySQL service
net stop mysql

Change root Password

Command:

1
mysqladmin -u root password 1234

Login parameters:

1
2
3
4
mysql -u username -p password -h ip_address (default 127.0.0.1) -P port (default 3306)
# Example
mysql -u root -p
# You will be prompted for the password after execution

Quick Start Example

First, create a SpringBoot project and select the MyBatis Framework and MySQL Driver dependencies.

  1. Database
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
create database mybatis;

use mybatis;

create table user(
    id int unsigned primary key auto_increment comment 'ID',
    name varchar(100) comment 'Name',
    age tinyint unsigned comment 'Age',
    gender tinyint unsigned comment 'Gender, 1: Male, 2: Female',
    phone varchar(11) comment 'Phone'
) comment 'User Table';

insert into user(id, name, age, gender, phone) VALUES (null,'Eagle King',55,'1','18800000000');
insert into user(id, name, age, gender, phone) VALUES (null,'Lion King',45,'1','18800000001');
insert into user(id, name, age, gender, phone) VALUES (null,'Bat King',38,'1','18800000002');
insert into user(id, name, age, gender, phone) VALUES (null,'Dragon King',42,'2','18800000003');
insert into user(id, name, age, gender, phone) VALUES (null,'Left Envoy',37,'1','18800000004');
insert into user(id, name, age, gender, phone) VALUES (null,'Right Envoy',48,'1','18800000005');
  1. application.properties
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Database connection settings

# Driver class name
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Connection URL
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
# Username
spring.datasource.username=root
# Password
spring.datasource.password=1234
  1. User Class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class User {
    private Integer id;
    private String name;
    private short age;
    private short gender;
    private String phone;

    public User() {
    }

    public User(Integer id, String name, short age, short gender, String phone) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public short getAge() {
        return age;
    }

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

    public short getGender() {
        return gender;
    }

    public void setGender(short gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                ", phone='" + phone + '\'' +
                '}';
    }
}
  1. UserMapper Interface
1
2
3
4
5
6
@Mapper // At runtime, an implementation (proxy object) is automatically generated and managed by the IOC container
public interface UserMapper {
    // Using annotations for SQL statements
    @Select("select * from user")
    public List<User> list();
}
  1. Test Class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@SpringBootTest
class MybatisStartApplicationTests {
    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        List<User> list = userMapper.list();
        list.forEach(System.out::println);
    }

}

Database Connection Pool

A database connection pool is a container that manages database connections (Connection).

It allows the application to reuse existing connections instead of creating a new one every time. It also closes connections that have been idle too long to prevent connection leaks.

Benefits: Resource reuse and faster system response.

The official standard interface is DataSource.

Common implementations: Hikari (SpringBoot default), Druid.

Lombok

In the previous example, the User class was bloated with boilerplate code for just a few fields. Use Lombok to clean this up.

Lombok is a Java library that uses annotations to automatically generate constructors, getters/setters, equals, hashcode, toString, and log variables, significantly improving development efficiency.

AnnotationDescription
@Getter/@SetterProvides get/set methods for all fields
@ToStringAutomatically generates a readable toString method
@EqualsAndHashCodeOverwrites equals and hashCode methods based on non-static fields
@DataCombined functionality (@Getter+@Setter+@ToString+@EqualsAndHashCode)
@NoArgsConstructorGenerates a no-args constructor
@AllArgsConstructorGenerates a constructor for all non-static fields

Adding Lombok

Add the dependency. No version number is needed as SpringBoot handles it.

1
2
3
4
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

User Class with Lombok

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
    private short age;
    private short gender;
    private String phone;
}

Lombok generates the Java code during compilation. You’ll need the Lombok plugin in your IDE, though IntelliJ IDEA has it installed by default.

This post is licensed under CC BY-NC-SA 4.0 by the author.
Last updated on 2025-02-05 16:35 +0900