您可以使用自定义的Hibernate命名策略来实现此目标。
您只需要使用开源项目hibernate-types
即可。
Hibernate 5.2或更高版本
您需要添加以下Maven依赖项:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
并设置以下 Hibernate 配置属性:
<property name="hibernate.physical_naming_strategy"
value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>
Hibernate 5.0和5.1
您需要添加以下Maven依赖项:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-5</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
并设置以下 Hibernate 配置属性:
<property name="hibernate.physical_naming_strategy"
value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>
Hibernate 4.3
您需要添加以下Maven依赖项:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-43</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
并设置以下Hibernate配置属性:
<property name="hibernate.ejb.naming_strategy"
value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>
Hibernate 4.2和4.1
您需要添加以下Maven依赖:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-4</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
并设置以下 Hibernate 配置属性:
<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;
}
@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;
}
使用CamelCaseToSnakeCaseNamingStrategy
自定义命名策略时,Hibernate将使用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)
)
很酷,对吧?
@DatabaseIsUnderscoreAndThisAnnotationConvertsThemToCamelCaseByDefault
... 开玩笑的,但我真的想把这个贴给我的朋友。 :) - Kenny Cason