在 Spring Boot 中使用 Hibernate(通常是通过 Spring Data JPA 来集成 Hibernate 作为默认的 JPA 实现),Spring Boot 提供了一系列 自动配置项 来简化开发配置。以下是主要的自动配置项,按功能进行分类:
一、数据源相关(DataSource)
spring.datasource.url
spring.datasource.username
spring.datasource.password
spring.datasource.driver-class-name
spring.datasource.hikari.*
(默认使用 HikariCP 连接池)
二、JPA 相关配置(自动配置类:JpaProperties
)
spring.jpa.database
指定数据库类型,例如:mysql
,postgresql
,默认自动检测spring.jpa.show-sql
是否显示 SQL 语句,默认:false
spring.jpa.properties.*
用于设置传给 Hibernate 的原生属性,例如:spring.jpa.properties.hibernate.format_sql
spring.jpa.properties.hibernate.use_sql_comments
spring.jpa.properties.hibernate.dialect
spring.jpa.hibernate.ddl-auto
Hibernate 的 DDL 策略,常见值:none
:不做任何 DDL 操作validate
:验证实体和表结构是否一致update
:自动更新表结构(开发常用)create
:启动时创建表,退出时删除create-drop
:启动时创建,关闭时删除- 默认:
none
(从 Spring Boot 2.5 起)
三、实体扫描相关
spring.jpa.entity.scan.*
默认会扫描启动类所在包及其子包中的@Entity
注解类,通常不需要额外配置
四、事务管理
spring.jpa.open-in-view
是否启用 Open Session in View 模式,默认:true
(会延长 session 生命周期直到 view 渲染结束)
五、SQL 初始化脚本
spring.sql.init.mode=always
控制是否执行 SQL 脚本(如 schema.sql、data.sql)
六、多数据源支持(需手动配置)
Spring Boot 默认只配置一个主数据源。若使用多个数据源,则需要手动指定 EntityManagerFactory、TransactionManager 等。
七、自动配置类(Spring Boot 中负责 JPA 配置的类)
DataSourceAutoConfiguration
HibernateJpaAutoConfiguration
JpaRepositoriesAutoConfiguration
DataSourceTransactionManagerAutoConfiguration
如果你希望查看实际生效的配置,可以使用:
$ ./mvnw spring-boot:run -Dspring-boot.run.arguments=--debug
或在运行时访问 /actuator/configprops
(需启用 Actuator)。