Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming strategy of columns in spring boot 2

how can I configure spring to using underscore in columns without explicitly defined in @Column? For instance if I have column in entity like this:

@LastModifiedBy
private String changedBy;

I want to map it to physical column in database which is changed_by

I tried to configure it with property spring.jpa.hibernate.naming.physical-strategy to SpringPhysicalNamingStrategy or PhysicalNamingStrategyStandardImpl but I always got exception ERROR: column "changedby" of relation "xxxx" does not exist

like image 354
Denis Stephanov Avatar asked Nov 22 '19 18:11

Denis Stephanov


1 Answers

In my setup (Postgres, Flyway), I achieve this using the hybernate-types package: https://github.com/vladmihalcea/hibernate-types . This will give you a ready-to-use implementation for the naming strategy: CamelCaseToSnakeCaseNamingStrategy

You can configure this in XML like this:

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

Alternatively, you can configure it in code (Kotlin in my case):


@Bean
fun entityManagerFactory(): LocalContainerEntityManagerFactoryBean {
    val jpaProperties = Properties().apply {
        put("hibernate.physical_naming_strategy", CamelCaseToSnakeCaseNamingStrategy::class.java.canonicalName)
        // ....
    }
    return LocalContainerEntityManagerFactoryBean().apply {
        setJpaProperties(properties)
        // ....
    }

See also https://vladmihalcea.com/map-camel-case-properties-snake-case-column-names-hibernate/ for further information.

like image 160
Dirk Bolte Avatar answered Sep 28 '22 10:09

Dirk Bolte