Home > Software design >  Spring boot application and hibernate are using different naming strategies
Spring boot application and hibernate are using different naming strategies

Time:03-09

This is very strange.

I am using the spring.jpa.generate-ddl=true to create the tables in my database. When spring does this, the table names are snake case. For example, the table for MyClass becomes my_class.

Next, I exported the schema from Hibernate using this code: Export schema from Hibernate

When I call the code, the resulting sql has table names in camel case with the first letter capitalized. So, the table for MyClass is MyClass.

Why would they generate differently? How do I get them to be the same?

CodePudding user response:

The table names are different because Spring configures Hibernate to use a different naming strategy. The naming strategy defines how Hibernate generates the logical name of an attribute or entity and how to map them to the physical name in the database. I explain that in more detail in the Naming Strategy Guide on my blog.

You have multiple options to ensure both of your setups use the same naming strategy:

If you're using a Hibernate version >= 5.5.4, you can configure it to use the CamelCaseToUnderscoresNamingStrategy. That's the one that Spring is using by default:

<persistence>
    <persistence-unit name="my-persistence-unit">
        ...
 
        <properties>
            ...
             
            <property name="hibernate.physical_naming_strategy"
                      value="org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy"/>
        </properties>
    </persistence-unit>
</persistence>

If you're using an older Hibernate version, you might want to change Spring's naming strategy to Hibernate's default strategy. You can do that by setting the following property in your application.properties file:

spring.jpa.properties.hibernate.implicit_naming_strategy=default

If you're using an older Hibernate version and want to use Spring's naming strategy, you have to implement a custom naming strategy. This isn't complex, and I explain how to do it in my blog post, but I would choose one of the previously mentioned solutions.

  • Related