11

By default, my Spring Boot project had JPA mapping entity properties to table columns by transforming the names from camelCase to snake_case (e.g. from fooBar to foo_bar).

I'm working on an existing DB, where the entity property names were kept as is for the table column names (e.g. from fooBar to fooBar), so I tried to use the @Column annotation to explicitly specify the name:

@Column(name = "fooBar")
private String fooBar;

This wasn't working. I followed the advice given here:

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

My @Column is now successfully taken into account, but I'm losing the camelCase to snake_case implicit transformation on the properties that don't have the @Column the annotation.

Any idea how to transform from camelCase to snake_case by default, unless explicitly specified in the @Column annotation?

sp00m
  • 47,968
  • 31
  • 142
  • 252
  • @YCF_L MySQL. As I said, `@Column` is now working successfully, but the implicit transformation is not to snake_case anymore. – sp00m Jun 14 '18 at 13:37
  • Yes I understand, just curious why you want to be like that ? – Youcef LAIDANI Jun 14 '18 at 13:39
  • @YCF_L Well I think snake_case is more common for SQL entities (kind of unofficial conventions), so the new entities I'm adding should be snake_cased, but I still need to deal with legacy tables that don't follow this convention. We'll rename the existing tables in a second phase. – sp00m Jun 14 '18 at 13:45

2 Answers2

3

Somehow the default JPA behavior of converting to snake case was not working when I injected my custom spring datasource beans for my H2 and postgres repositories. I wanted to convert camel case to snake case by default without explicitly annotating columns while saving objects to DB. Hence adding below property in application.properties worked for me:

spring.jpa.properties.hibernate.physical_naming_strategy: org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy

Note: I am using spring boot version 2.6.2

Ady
  • 584
  • 8
  • 16
0

Automatically transforming property-Names using camelCase (as is the naming convention in Java) to SNAKE_CASE seems to be no longer supported as of Hibernate 5. However, you can write your own Implementation of a NamingStrategy, doing exactly that. Please check this Stackoverflow-Answer to see how it is done.

Iris Hunkeler
  • 208
  • 1
  • 10