默认情况下,我的 Spring Boot 项目通过将名称从camelCase 转换为snake_case(例如从
fooBar
到foo_bar
),将实体属性映射到表列。
我正在开发一个现有的数据库,其中实体属性名称保留为表列名称(例如从
fooBar
到 fooBar
),因此我尝试使用 @Column
注释来显式指定名称:
@Column(name = "fooBar")
private String fooBar;
这不起作用。我遵循了here给出的建议:
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
我的
@Column
现在已成功考虑在内,但我在没有 @Column
注释的属性上失去了从camelCase到snake_case的隐式转换。
知道如何默认从camelCase转换为snake_case,除非在
@Column
注释中明确指定?
当我为 H2 和 postgres 存储库注入自定义 Spring 数据源 bean 时,转换为蛇形大小写的默认 JPA 行为不知何故不起作用。我想默认将驼峰式大小写转换为蛇式大小写,而无需在将对象保存到数据库时显式注释列。因此,在 application.properties 中添加以下属性对我有用:
spring.jpa.properties.hibernate.physical_naming_strategy: org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy
注意:我使用的是 Spring Boot 版本 2.6.2
从 Hibernate 5 开始,似乎不再支持使用驼峰命名法(Java 中的命名约定)将属性名称自动转换为 SNAKE_CASE。但是,您可以编写自己的 NamingStrategy 实现,完全做到这一点。 请检查此 Stackoverflow-Answer 以了解它是如何完成的。
将其添加到您的 application.properties 文件中
spring.jpa.hibernate.naming.physical-strategy = org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.hibernate.naming.implicit-strategy = org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
Hier 是来源。 教程链接