一、核心概念

概念 说明
DataSource 数据源,负责数据库连接的创建和管理(如 HikariCP、Druid)
JDBC URL 连接数据库的地址,包含主机、端口、数据库名、参数等
Driver Class JDBC 驱动类名(MySQL 8 推荐使用 com.mysql.cj.jdbc.Driver
MyBatis-Plus Starter 自动集成 MyBatis 和 MyBatis-Plus,简化配置
MybatisPlusConfig 可选自定义配置类(如分页插件、SQL 日志、自动填充等)
application.yml / application.properties Spring Boot 配置文件,用于配置数据源和 MP 行为

二、详细操作步骤(Spring Boot + MySQL)

步骤 1:添加 Maven 依赖

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- MyBatis-Plus 启动器(含 MyBatis) -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.6</version> <!-- 推荐使用最新稳定版 -->
    </dependency>

    <!-- MySQL 驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!-- Lombok(可选) -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

🔔 注意:mybatis-plus-boot-starter 已内置 MyBatis 和默认配置,无需再引入 mybatis-spring-boot-starter


步骤 2:创建数据库和表(示例)

CREATE DATABASE mydb DEFAULT CHARSET utf8mb4;

USE mydb;

CREATE TABLE user (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    age INT,
    email VARCHAR(100),
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

步骤 3:配置 application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
    username: root
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource  # 默认数据源(Spring Boot 2+ 使用 HikariCP)

# MyBatis-Plus 配置
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  # 控制台打印 SQL(开发环境开启)
    map-underscore-to-camel-case: true                    # 驼峰命名自动转下划线(默认 true)
  global-config:
    db-config:
      id-type: auto                                       # 主键策略:数据库自增
      # logic-delete-value: 1                             # 逻辑删除值(可选)
      # logic-not-delete-value: 0                         # 未删除值(可选)
  mapper-locations: classpath*:mapper/*.xml               # XML 映射文件路径(可选)

📌 JDBC 参数说明

  • useSSL=false:关闭 SSL(本地开发)
  • serverTimezone=GMT%2B8:设置时区为东八区
  • allowPublicKeyRetrieval=true:允许公钥检索(MySQL 8+ 有时需要)
  • characterEncoding=UTF-8:防止中文乱码

步骤 4:创建实体类(User.java)

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.time.LocalDateTime;

@Data
@TableName("user") // 映射表名
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;

    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
}

步骤 5:创建 Mapper 接口

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
    // 无需实现方法,BaseMapper 提供通用 CRUD
}

步骤 6:启用 Mapper 扫描(主类)

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.mapper") // 扫描 Mapper 接口包
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

步骤 7:测试连接(Controller 示例)

@RestController
public class TestController {

    private final UserMapper userMapper;

    public TestController(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @GetMapping("/users")
    public List<User> getUsers() {
        return userMapper.selectList(null); // 查询所有
    }
}

启动项目,访问 http://localhost:8080/users,若返回空数组或数据,说明连接成功。


三、常见错误与解决方案

错误现象 原因 解决方案
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver 驱动未引入或版本不匹配 检查 mysql-connector-java 依赖是否正确
Unknown database 'mydb' 数据库不存在 创建数据库或修改 url 中的数据库名
Access denied for user 'root'@'localhost' 用户名/密码错误 检查 usernamepassword
The server time zone value 'XXX' is unrecognized 时区未设置 在 JDBC URL 中添加 serverTimezone=GMT%2B8
Invalid bound statement (not found) Mapper 未被扫描 检查 @MapperScan 路径是否正确
SQL 执行但无日志输出 未开启 SQL 日志 mybatis-plus.configuration.log-impl 中设置输出实现

四、注意事项

  1. MySQL 8+ 必须使用 mysql-connector-java 8.x 版本,驱动类为 com.mysql.cj.jdbc.Driver
  2. JDBC URL 中必须包含 serverTimezone,否则会报时区错误。
  3. 生产环境不要开启 log-impl,避免日志过多影响性能。
  4. HikariCP 是默认高性能连接池,无需额外配置。
  5. @MapperScan 必须扫描到你的 Mapper 接口,否则无法注入。

五、使用技巧

✅ 1. 多环境配置(application-dev.yml / application-prod.yml

# application-dev.yml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb_dev?...
    username: dev_user
    password: dev_pass

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 开发环境开启日志
# application-prod.yml
spring:
  datasource:
    url: jdbc:mysql://prod-db:3306/mydb?...
    username: prod_user
    password: ${DB_PASSWORD} # 使用环境变量

mybatis-plus:
  configuration:
    log-impl: # 生产环境关闭日志

启动时指定环境:--spring.profiles.active=prod


✅ 2. 使用 Druid 数据源(增强监控)

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.20</version>
</dependency>

配置:

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 5
      min-idle: 5
      max-active: 20
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        login-username: admin
        login-password: admin

✅ 3. 自定义 MyBatis-Plus 配置类(如分页插件)

@Configuration
@MapperScan("com.example.mapper")
public class MyBatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

⚠️ 如果使用了 mybatis-plus-boot-starter,此配置类可自动被识别。


六、最佳实践与性能优化

实践 说明
✅ 使用连接池(HikariCP/Druid) 提升连接复用效率
✅ 合理设置连接池参数 maximumPoolSize=20,避免资源耗尽
✅ 关闭生产环境 SQL 日志 防止日志文件过大
✅ 使用 @MapperScan 而非 @Mapper 避免每个 Mapper 都加注解
✅ 统一异常处理 捕获 PersistenceException 等数据库异常
✅ 使用 Wrapper 构建安全查询 避免 SQL 注入
✅ 合理使用缓存 结合 Redis 缓存高频查询结果
✅ 定期监控慢查询 通过数据库慢日志或 APM 工具

七、总结:数据库连接配置要点

项目 推荐值
驱动类 com.mysql.cj.jdbc.Driver
JDBC URL 参数 useSSL=false&serverTimezone=GMT%2B8&characterEncoding=UTF-8
数据源类型 HikariDataSource(默认)或 DruidDataSource
MyBatis-Plus Starter mybatis-plus-boot-starter
SQL 日志 开发开启,生产关闭
主键策略 IdType.AUTO(自增)或 IdType.ASSIGN_ID(雪花)
驼峰映射 map-underscore-to-camel-case: true(默认)

现在你已经掌握了 MyBatis-Plus 的数据库连接配置全流程!
只需按照上述步骤操作,即可快速搭建一个稳定、高效的数据库访问层。

🌐 官方文档:https://baomidou.com
📚 推荐:使用 MyBatis-Plus Code Generator 自动生成代码,提升开发效率。