Uppercase table names in Spring Boot

tleipzig

Thomas

Posted on March 25, 2024

Uppercase table names in Spring Boot

In Spring Boot / Hibernate, the table name is derived from the entity name. What must our naming strategy look like to translate all table names to uppercase?

Without further configuration, the physical name of the entity is converted to lowercase with underscores - so our class LineItem becomes the table line_item. We could try to store the adjusted name at each table with @Table(name = "LINE_ITEM") to overwrite the physical name - but would still need to change the naming strategy, because otherwise it would be changed back to lowercase after all.

Therefore the best approach is to provide the transformation for all table names with a dedicated naming strategy. Additional information within the @Table annotation is no longer necessary.

public class CamelCaseToUppercaseTablesNamingStrategy extends CamelCaseToUnderscoresNamingStrategy {

    private Identifier adjustName(final Identifier name) {
        if (name == null) {
            return null;
        }
        final String adjustedName = name.getText().toUpperCase();
        return new Identifier(adjustedName, true);
    }

    @Override
    public Identifier toPhysicalTableName(final Identifier name, final JdbcEnvironment context) {
        return adjustName(super.toPhysicalTableName(name, context));
    }

}
Enter fullscreen mode Exit fullscreen mode

  Customization of all table names using a custom naming strategy

Our naming strategy extends from CamelCaseToUnderscoresNamingStrategy so that all other methods (e.g. for the field names) still apply. The table name is first changed to lowercase with underscores, and then altered to uppercase in adjustName.

All adjusted identifiers are automatically created with quoted = true. This prevents the database from changing the table name and the name is taken over exactly. Finally only one entry in our application.yml / application.properties is missing.

spring.jpa.hibernate.naming.physical-strategy=io.bootify.my_app.config.CamelCaseToUppercaseTablesNamingStrategy
Enter fullscreen mode Exit fullscreen mode

With this, Hibernate / Spring Data translates all physical names to uppercase with underscores. We could also override the toColumnTableName method if we also want to translate the field names as well. With a little adjustment, camel case would also be possible as output.

Bootify allows to create any custom database schema for your next Spring Boot application - directly in the browser, without registration. In the Professional plan, four additional Naming Strategies are available for selection and directly provide the configured, executable application.

» See Features and Pricing

💖 💪 🙅 🚩
tleipzig
Thomas

Posted on March 25, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related