如何配置 spring 在列中使用下划线而不在 @Column
中明确定义?例如,如果我在实体中有这样的列:
@LastModifiedBy
private String changedBy;
我想将其映射到数据库中的物理列,该列是changed_by
我尝试使用属性spring.jpa.hibernate.naming.physical-strategy
将其配置为SpringPhysicalNamingStrategy或PhysicalNamingStrategyStandardImpl,但我总是得到异常错误:关系“xxxx”的列“changedby”不存在
最佳答案
在我的设置(Postgres
、Flyway
)中,我使用 hybernate-types
包实现了这一点:https://github.com/vladmihalcea/hibernate-types 。这将为您提供一个现成的命名策略实现:CamelCaseToSnakeCaseNamingStrategy
您可以像这样在 XML 中进行配置:
<property name="hibernate.physical_naming_strategy"
value="com.vladmihalcea.hibernate.type.util.CamelCaseToSnakeCaseNamingStrategy"/>
或者,您可以在代码中配置它(在我的例子中是 Kotlin):
@Bean
fun entityManagerFactory(): LocalContainerEntityManagerFactoryBean {
val jpaProperties = Properties().apply {
put("hibernate.physical_naming_strategy", CamelCaseToSnakeCaseNamingStrategy::class.java.canonicalName)
// ....
}
return LocalContainerEntityManagerFactoryBean().apply {
setJpaProperties(properties)
// ....
}
另请参阅https://vladmihalcea.com/map-camel-case-properties-snake-case-column-names-hibernate/欲了解更多信息。
关于spring - Spring Boot 2中列的命名策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59000152/