简体   繁体   English

如何 map Hibernate 实体字段使用camelCase到snake_case(下划线)数据库标识符

[英]How to map Hibernate entity fields using camelCase to snake_case (underscore) database identifiers

I have database fields in underscore.我有下划线的数据库字段。 I have entity fields in camelcase.我在驼峰式中有实体字段。 I can't change either of those.我无法改变其中任何一个。

Is there something, maybe a class level annotation I can use to default entity column name annotations to the camelcase equivalent?有什么东西,也许是 class 级别的注释,我可以使用默认的实体列名注释到骆驼大小写等效项?

for example, I have an entity like this:例如,我有一个这样的实体:

@Entity
public class AuthorisationEntity {

    @Column(name = "non_recoverable")
    private BigDecimal nonRecoverable;

    @Column(name = "supplier_recoverable")
    private BigDecimal supplierRecoverable;

    @Column(name = "refund_amount")
    private BigDecimal refundAmount;

}

I dream of this:我梦想这个:

@Entity
@DatabaseIsUnderscoreAndThisAnnotationConvertsThemToCamelCaseByDefault
public class AuthorisationEntity {

    private BigDecimal nonRecoverable;

    private BigDecimal supplierRecoverable;

    private BigDecimal refundAmount;

}

You can achieve this using a custom Hibernate naming strategy.您可以使用自定义 Hibernate 命名策略来实现这一点。

All you need to do is to use the hibernate-types open-source project.您需要做的就是使用hibernate-types开源项目。

Hibernate 5.2 or later休眠 5.2 或更高版本

You need to add the following Maven dependency:您需要添加以下 Maven 依赖项:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>${hibernate-types.version}</version>
</dependency>

And set the following Hibernate configuration property:并设置以下 Hibernate 配置属性:

<property name="hibernate.physical_naming_strategy"
          value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>

Hibernate 5.0 and 5.1休眠 5.0 和 5.1

You need to add the following Maven dependency:您需要添加以下 Maven 依赖项:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-5</artifactId>
    <version>${hibernate-types.version}</version>
</dependency>

And set the following Hibernate configuration property:并设置以下 Hibernate 配置属性:

<property name="hibernate.physical_naming_strategy"
          value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>

Hibernate 4.3休眠 4.3

You need to add the following Maven dependency:您需要添加以下 Maven 依赖项:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-43</artifactId>
    <version>${hibernate-types.version}</version>
</dependency>

And set the following Hibernate configuration property:并设置以下 Hibernate 配置属性:

<property name="hibernate.ejb.naming_strategy"
          value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>

Hibernate 4.2 and 4.1休眠 4.2 和 4.1

You need to add the following Maven dependency:您需要添加以下 Maven 依赖项:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-4</artifactId>
    <version>${hibernate-types.version}</version>
</dependency>

And set the following Hibernate configuration property:并设置以下 Hibernate 配置属性:

<property name="hibernate.ejb.naming_strategy"
          value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"
/>

Testing time测试时间

Assuming you have the following entities:假设您有以下实体:

@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
}

When using the CamelCaseToSnakeCaseNamingStrategy custom naming strategy, Hibernate is going to generate the following database schema using the hbm2ddl tool:当使用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)
)

Cool, right?酷,对吧?

You can use hibernate's naming strategy.您可以使用 hibernate 的命名策略。 Such naming strategy class describes how to generate database names for given java names.这样的命名策略类描述了如何为给定的 java 名称生成数据库名称。

See:看:

naming strategy example 命名策略示例

second example 第二个例子

very good oracle naming strategy - it converts camel to underscore convention, and much more 非常好的 oracle 命名策略- 它将骆驼转换为下划线约定,等等

I was experiencing the same problem in a Spring boot application, I tried adding the above Hibernate config to the spring properties file with no success, added it as a java bean, again with no success.我在 Spring 启动应用程序中遇到了同样的问题,我尝试将上述 Hibernate 配置添加到 spring 属性文件中,但没有成功,将其添加为 java bean,再次没有成功。

I am using Hibernate Properties object, adding the hibernate configuration within this solved my issue:我正在使用 Hibernate Properties对象,在其中添加休眠配置解决了我的问题:

        protected Properties buildHibernateProperties() {
        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
        hibernateProperties.setProperty("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());

        return hibernateProperties;
    }
import org.hibernate.cfg.DefaultNamingStrategy;
import org.hibernate.cfg.ImprovedNamingStrategy;

public class NamingStratagyTest {
    public static void main(String[] args) {
        String colName = DefaultNamingStrategy.INSTANCE.columnName("UserName");
        System.out.println(colName); // UserName
        colName = ImprovedNamingStrategy.INSTANCE.columnName("UserName");
        System.out.println(colName);// user_name
    }
}

There you go, choose the naming strategy that suits your need.好了,选择适合您需要的命名策略。

From Hibernate 5.5.4.Final , CamelCaseToUnderscoresNamingStrategy has been introduced, the new strategy is the equivalent of the Spring SpringPhysicalNamingStrategy .从 Hibernate 5.5.4.Final ,引入了CamelCaseToUnderscoresNamingStrategy ,新策略相当于 Spring SpringPhysicalNamingStrategy

The CamelCaseToUnderscoresNamingStrategy replaces all dots with underscores, all camel casing with underscores and generates all table names in lower case. CamelCaseToUnderscoresNamingStrategy将所有点替换为下划线,所有驼峰大小写替换为下划线,并生成所有小写的表名。

For example, the LineItem entity will be mapped to the line_item table.例如, LineItem实体将映射到line_item表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JAVA - 不使用 ObjectMapping 和 SetPropertyNamingStrategy 将 CamelCase 转换为 Snake_Case - SNAKE_CASE - JAVA - Not converting CamelCase to Snake_Case using ObjectMapping and SetPropertyNamingStrategy - SNAKE_CASE 如何将firebase数据(snake_case)转换为Java对象(camelCase) - How to convert firebase data (snake_case) to Java object (camelCase) Webclient + Jackson:如何设置反序列化将snake_case转换为camelCase? - Webclient + Jackson: how to setup deserialization to convert snake_case into camelCase? 如何使用Jackson将蛇案Yaml映射到camelcase Java字段 - How to map snake case yaml to camelcase java fields with Jackson Java中从snake_case到camelCase - From snake_case to camelCase in Java 如何防止 Spring Boot/Hibernate 将实体列名称从 PascalCase 转换为 snake_case? - How to prevent Spring Boot/Hibernate from converting entity column names from PascalCase to snake_case? 除非明确指定,否则如何在默认情况下将 Spring Data JPA 从 camelCase 命名为 snake_case? - How to make Spring Data JPA by default naming from camelCase to snake_case unless explicitly specified? Jackson / Spring Boot - 将 snake_case model 序列化为 camelCase - Jackson / Spring Boot - serialize a snake_case model to camelCase 如何解析 SnakeYAML 中的 snake_case 属性 - How to parse snake_case properties in SnakeYAML SpringBoot:如何将蛇案例转换为骆驼案例 - SpringBoot: How to convert snake case to camelCase
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM