您可以使用自定义休眠命名策略来实现此目的。
您需要做的就是使用开源项目。hibernate-types
休眠 5.2 或更高版本
您需要添加以下 Maven 依赖项:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
并设置以下休眠配置属性:
<property name="hibernate.physical_naming_strategy"
value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>
休眠 5.0 和 5.1
您需要添加以下 Maven 依赖项:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-5</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
并设置以下休眠配置属性:
<property name="hibernate.physical_naming_strategy"
value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>
休眠 4.3
您需要添加以下 Maven 依赖项:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-43</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
并设置以下休眠配置属性:
<property name="hibernate.ejb.naming_strategy"
value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>
休眠 4.2 和 4.1
您需要添加以下 Maven 依赖项:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-4</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
并设置以下休眠配置属性:
<property name="hibernate.ejb.naming_strategy"
value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>
测试时间
假设您具有以下实体:
@Entity(name = "BookAuthor")
public class BookAuthor {
@Id
private Long id;
private String firstName;
private String lastName;
//Getters and setters omitted for brevity
}
@Entity(name = "PaperBackBook")
public class PaperBackBook {
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE
)
private Long id;
@NaturalId
private String ISBN;
private String title;
private LocalDate publishedOn;
@ManyToOne(fetch = FetchType.LAZY)
private BookAuthor publishedBy;
//Getters and setters omitted for brevity
}
使用自定义命名策略时,Hibernate 将使用该工具生成以下数据库架构:CamelCaseToSnakeCaseNamingStrategy
hbm2ddl
CREATE SEQUENCE hibernate_sequence
START WITH 1 INCREMENT BY 1
CREATE TABLE book_author (
id BIGINT NOT NULL,
first_name VARCHAR(255),
last_name VARCHAR(255),
PRIMARY KEY (id)
)
CREATE TABLE paper_back_book (
id BIGINT NOT NULL,
isbn VARCHAR(255),
published_on DATE,
title VARCHAR(255),
published_by_id BIGINT,
PRIMARY KEY (id)
)
很酷,对吧?