Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Getting Started with MyBatis-Plus for Efficient Database Operations

Tech 3

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

  1. 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>
    
  2. 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');
    
  3. 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

  1. Define Entity Class

    import lombok.Data;
    @Data
    public class Employee {
        private Long id;
        private String fullName;
        private Integer years;
        private String contactEmail;
    }
    
  2. Create Mapper Interface

    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import org.apache.ibatis.annotations.Mapper;
    @Mapper
    public interface EmployeeMapper extends BaseMapper<Employee> {}
    
  3. 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);
        }
    }
    
  4. 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);
        }
    }
    

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.