配置指南 - 项目配置
说明
Smart Mybatis 提供了多种依赖, 其中最常用的依赖是 spring-boot-starter-smart-mybatis, 它集成了 Smart Mybatis 的核心功能, 并且与 Spring Boot 无缝集成, 适合大多数项目使用。
本章节将介绍如何在Spring Boot中配置 Smart Mybatis 以满足不同的需求。
完整配置
Smart MyBatis 的配置项均以 spring.mybatis.smart 为前缀,可以在 application.properties 或 application.yaml 中配置。
spring:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:smart_mybatis;MODE=MySQL;DATABASE_TO_UPPER=true;DB_CLOSE_DELAY=-1
username: sa
password:
mybatis:
smart:
enabled: true
auto-sync-db: false
naming-convention: underline_upper
table-prefix: sm_
# dialect-driver-class-name: org.h2.Driver
Properties 等价写法:
spring.mybatis.smart.enabled=true
spring.mybatis.smart.auto-sync-db=false
spring.mybatis.smart.naming-convention=underline_upper
spring.mybatis.smart.table-prefix=sm_
# spring.mybatis.smart.dialect-driver-class-name=org.h2.Driver
配置项详解
| 配置项 | 默认值 | 说明 |
|---|---|---|
enabled | true | 是否执行 SmartMapper 初始化增强。关闭后保留原生 MyBatis 行为。 |
auto-sync-db | false | 是否根据实体元数据自动建表、补列或调整列定义。 |
naming-convention | underline_upper | 实体和字段的默认命名转换规则。 |
table-prefix | 空字符串 | 添加到推导表名前的统一前缀。 |
dialect-driver-class-name | 空字符串 | 显式指定用于匹配方言的 JDBC driver class。为空时读取 spring.datasource.driver-class-name。 |
enabled
enabled=false 会跳过 SmartMapper 的初始化增强,包括自动同步、主键回填补丁、JSON ResultMap 和初始化脚本。它不会卸载 MyBatis,也不会影响已有 XML、注解 SQL 和 MyBatis 插件。
naming-convention
指定实体与数据库之间默认的的命名转换规则。可选值包括:
| 取值 | 描述 | 是否默认 |
|---|---|---|
underline_upper | 驼峰转大写下划线 (如 userName 转为 USER_NAME) | 是 |
underline_lower | 驼峰转小写下划线 (如 userName 转为 user_name) | 否 |
as_is | 不进行任何转换, 使用Java实体原名称作为数据库表和列名 | 否 |
table-prefix
指定数据库表的前缀, 例如设置为 sm_ 后, 实体 User 将映射到数据库表 SM_USER。
此选项可与 naming-convention 配合使用, 以确保生成的表名符合项目规范。比如, 对于实体 UserProfile 且 table-prefix 设置为 sm_:
- 若
naming-convention设置为underline_upper, 则映射到表SM_USER_PROFILE。 - 若
naming-convention设置为underline_lower, 则映射到表sm_user_profile。 - 若
naming-convention设置为as_is, 则映射到表sm_UserProfile。 - 若不设置
table-prefix, 则仅根据naming-convention生成表名。
auto-sync-db
默认值为 false。设置为 true 后,应用启动时会读取数据库元数据,并通过当前数据库方言生成建表或字段变更 SQL。
警告
启用此功能可能会对生产环境的数据库造成不可预期的更改, 请谨慎使用, 建议仅在开发阶段启用此功能, 以减少手动维护数据库表结构的工作量。
Smart MyBatis 不会删除实体中已移除的数据库列。字段改名、数据迁移、回滚和生产环境变更历史应交给 Flyway、Liquibase 等迁移工具。
dialect-driver-class-name
通常无需配置。Starter 会自动读取:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
当数据源未暴露 driver class,或需要显式选择方言时,可配置:
spring:
mybatis:
smart:
dialect-driver-class-name: com.mysql.cj.jdbc.Driver
无法识别的驱动当前会回退到 MySQL 方言,因此接入新数据库时应显式实现并验证方言,不能依赖兜底行为。
