1. 简介

在本篇文章中,我们将深入探讨如何在 Spring Boot 应用中使用 Hibernate 的命名策略。对于那些希望更灵活地控制数据库表结构和字段映射的开发者来说,掌握这些策略是很有必要的。

2. Maven 依赖配置

如果你已经有一个基于 Maven 的 Spring Boot 项目 并打算集成 Spring Data,那么只需要添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

此外,为了演示方便,我们还会引入 H2 内存数据库:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

✅ 注意:Spring Data JPA 已经默认引入了 Hibernate 相关依赖。

3. Spring Boot 中的命名策略机制

Hibernate 在进行字段到列的映射时,会使用两种策略:

  • 物理命名策略(Physical Naming Strategy)
  • 隐式命名策略(Implicit Naming Strategy)

我们曾在之前的 Hibernate 命名策略教程 中详细讨论过这两种策略的作用。

而在 Spring Boot 中,默认配置如下:

  • spring.jpa.hibernate.naming.physical-strategy 默认为:

    org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
    
  • spring.jpa.hibernate.naming.implicit-strategy 默认为:

    org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
    

这两个默认策略的行为包括:

✅ 将点号(.)替换为下划线(_
✅ 将驼峰命名转换为蛇形命名(snake_case)
✅ 表名统一转为小写

举个例子,一个名为 AddressBook 的实体类会被映射为 address_book 表。

4. 实战示例:默认策略效果

我们来创建一个简单的 Account 实体类:

@Entity
public class Account {
    @Id 
    private Long id;
    private String defaultEmail;
}

并在 application.propertiesapplication.yml 中开启 SQL 日志输出:

hibernate.show_sql=true

启动应用后,你会看到类似下面的建表语句出现在日志中:

Hibernate: create table account (id bigint not null, default_email varchar(255))

⚠️ 可以看到,字段名已经自动从 defaultEmail 转换成了 default_email,完全符合 Spring Boot 的默认命名规则。

📌 重点提示:在这种情况下,我们无需显式指定 physical-strategyimplicit-strategy,因为 Spring Boot 已经帮我们做了默认配置。

5. 自定义命名策略

如果我们要使用 JPA 1.0 的传统命名方式,可以按如下方式修改配置。

5.1 修改配置文件方式

application.yml 中添加:

spring:
  jpa:
    hibernate:
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl

5.2 使用 @Bean 方式注入策略

也可以通过 Java 配置类注入 Bean:

@Bean
public PhysicalNamingStrategy physical() {
    return new PhysicalNamingStrategyStandardImpl();
}

@Bean
public ImplicitNamingStrategy implicit() {
    return new ImplicitNamingStrategyLegacyJpaImpl();
}

无论哪种方式,在重新运行程序后,你将看到如下建表语句:

Hibernate: create table Account (id bigint not null, defaultEmail varchar(255), primary key (id))

✅ 这时候表名和字段名都保留了原始命名风格,没有做任何 snake_case 转换。

📌 扩展提示:如果你想启用 JPA 2.0 的兼容命名规则,只需将 implicit-strategy 设置为:

org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl

6. 总结

本文我们介绍了 Spring Boot 是如何整合 Hibernate 的命名策略,并展示了如何根据项目需求自定义这些策略。合理使用命名策略可以帮助我们在开发过程中更好地控制数据库结构与代码模型之间的映射关系。

📌 想查看完整代码?欢迎访问 GitHub 示例仓库: 👉 https://github.com/eugenp/tutorials/tree/master/persistence-modules/spring-boot-persistence


原始标题:Hibernate Field Naming with Spring Boot | Baeldung