Spring Boot 2中列的命名策略

时间:2019-11-22 18:53:52

标签: spring hibernate spring-boot jpa spring-data-jpa

如何配置spring以在@Column中未明确定义的列中使用下划线?例如,如果我在这样的实体中有专栏:

@LastModifiedBy
private String changedBy;

我想将其映射到changed_by数据库中的物理列

我尝试将其属性spring.jpa.hibernate.naming.physical-strategy配置为 SpringPhysicalNamingStrategy PhysicalNamingStrategyStandardImpl ,但我总是遇到异常ERROR: column "changedby" of relation "xxxx" does not exist

3 个答案:

答案 0 :(得分:2)

您可以使用custom naming for snake case

  

我们可以告诉Hibernate使用我们的新策略:

hibernate.physical_naming_strategy=com.baeldung.hibernate.namingstrategy.CustomPhysicalNamingStrategy

public class CustomPhysicalNamingStrategy implements PhysicalNamingStrategy {     
    @Override
    public Identifier toPhysicalCatalogName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return convertToSnakeCase(identifier);
    }     
    @Override
    public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return convertToSnakeCase(identifier);
    }     
    @Override
    public Identifier toPhysicalSchemaName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return convertToSnakeCase(identifier);
    }     
    @Override
    public Identifier toPhysicalSequenceName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return convertToSnakeCase(identifier);
    }     
    @Override
    public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return convertToSnakeCase(identifier);
    }     
    private Identifier convertToSnakeCase(final Identifier identifier) {
        final String regex = "([a-z])([A-Z])";
        final String replacement = "$1_$2";
        final String newName = identifier.getText()
          .replaceAll(regex, replacement)
          .toLowerCase();
        return Identifier.toIdentifier(newName);
    }
}

答案 1 :(得分:2)

在我的设置(PostgresFlyway)中,我使用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/

答案 2 :(得分:0)

您可以使用@Column手动指定列名:

     @LastModifiedBy
     @Column(name="changed_by")
     private String changedBy;