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:
| |
Wait a moment; a data folder will be generated in the MySQL directory.
Register MySQL Service
Command:
| |
Start MySQL Service
Commands:
| |
Change root Password
Command:
| |
Login parameters:
| |
Quick Start Example
First, create a SpringBoot project and select the MyBatis Framework and MySQL Driver dependencies.
- Database
| |
- application.properties
| |
- User Class
| |
- UserMapper Interface
| |
- Test Class
| |
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.
| Annotation | Description |
|---|---|
| @Getter/@Setter | Provides get/set methods for all fields |
| @ToString | Automatically generates a readable toString method |
| @EqualsAndHashCode | Overwrites equals and hashCode methods based on non-static fields |
| @Data | Combined functionality (@Getter+@Setter+@ToString+@EqualsAndHashCode) |
| @NoArgsConstructor | Generates a no-args constructor |
| @AllArgsConstructor | Generates a constructor for all non-static fields |
Adding Lombok
Add the dependency. No version number is needed as SpringBoot handles it.
| |
User Class with Lombok
| |
Lombok generates the Java code during compilation. You’ll need the Lombok plugin in your IDE, though IntelliJ IDEA has it installed by default.