Getting Started with MyBatis-Plus for Efficient Database Operations
MyBatis-Plus is a powerful enhancement framework for MyBatis that automates common CRUD operations, significantly reducing development time. It integrates seamlessly without altering existing MyBatis configurations, providing a smooth experience with minimal performance overhead.
Key Features
- Non-Invasive Design: Enhances MyBatis functionality without modifying core behavior, ensuring compatibility with existing projects.
- Efficient CRUD Operations: Built-in generic Mapper and Service interfaces automate standard database operations with minimal configuration.
- Lambda Support: Enables type-safe query construtcion using lambda expressions, eliminating field name errors.
- Primary Key Generation: Supports multiple strategies including distributed unique ID generation via Sequence.
- ActiveRecord Pattern: Allows entities to inherit from Model class for direct CRUD operations.
- Global Operations: Provides reusable global methods for common tasks.
- Code Generator: Quickly generates Model, Mapper, Service, and Controller code via Maven plugin or standalone tool.
- Built-in Pagination: Database-agnostic pagination plugin smiplifies paging queries.
- Performance Analysis: Outputs SQL statements and execution times to identify slow queries.
- SQL Interceptor: Prevents accidental full-table updates or deletes with configurable rules.
Quick Setup Guide
-
Add Dependencies Include the following in your
pom.xml:<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.3</version> </dependency> -
Database Setup Create a database and table:
CREATE DATABASE demo_db; USE demo_db; CREATE TABLE employee ( id BIGINT PRIMARY KEY COMMENT 'Primary Key', full_name VARCHAR(30) COMMENT 'Employee Name', years INT COMMENT 'Age', contact_email VARCHAR(50) COMMENT 'Email Address' ); INSERT INTO employee (id, full_name, years, contact_email) VALUES (1, 'Alice', 25, 'alice@example.com'), (2, 'Bob', 30, 'bob@example.com'), (3, 'Charlie', 28, 'charlie@example.com'); -
Application Configuration Configure
application.properties:spring.datasource.url=jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=UTC spring.datasource.username=db_user spring.datasource.password=db_password
Implementation Example
-
Define Entity Class
import lombok.Data; @Data public class Employee { private Long id; private String fullName; private Integer years; private String contactEmail; } -
Create Mapper Interface
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; @Mapper public interface EmployeeMapper extends BaseMapper<Employee> {} -
Enable Mapper Scanning Add to your main application class:
import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan("com.example.mapper") @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } -
Execute Queries
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.junit.jupiter.api.Test; import java.util.List; @SpringBootTest public class DatabaseTest { @Autowired private EmployeeMapper dataMapper; @Test public void fetchAllRecords() { List<Employee> records = dataMapper.selectList(null); records.forEach(System.out::println); } }