Hibernate : How to change the auto generated foreign key column name from lowercase to uppercase

Viewed 314

I am migrating old spring boot application to latest spring boot 2.3.0

Migration happens successfully, however, when I try to connect the application to the existing database, it is not able to identify autogenerated foreign key columns due to uppercase and lowercase issue.

the foreign key column name in the older version had upper case letters as shown below. here, FLAGCATEGORY_FLAGCATEGORYID is the foreign key column name which is autogenerated by hibernate

enter image description here

When I use the new spring boot version with hibernate 5, it is generating lowercase foreign key column names. Due to this difference, the application can not be started with the older database. Could anybody suggest me what should I do to resolve this without changing the database schema? enter image description here

here is how the new foreign key table name looks like. foreign key column name now has lowercase letters enter image description here

2 Answers

You can use your own column names instead of the auto-generated ones, try adding this annotation on your flagCategory getter:

@JoinColumn(name = "FLAGCATEGORY_FLAGCATEGORYID")

Hibernate resolves a logical name to a physical name using PhysicalNamingStrategy contract. The default implementation is to simply use the logical name as the physical name.

You can define a custom implementation:

public class FooPhysicalNamingStrategy implements PhysicalNamingStrategy {

    // Changing the column names to upper case
    @Override
    public Identifier toPhysicalColumnName(Identifier identifier,
                                           JdbcEnvironment jdbcEnvironment) {
        
        return jdbcEnvironment
                .getIdentifierHelper()
                .toIdentifier(identifier.getText().toUpperCase(), identifier.isQuoted());
    }

    // Keeping as it is
    @Override
    public Identifier toPhysicalSchemaName(Identifier identifier, 
                                           JdbcEnvironment jdbcEnvironment) {
        
        return identifier;
    }

    // Other overridden methods    
}

And set hibernate.physical_naming_strategy setting to the FQN of the class or to reference the class.

For example, add the following property to your persistence-unit in persistence.xml:

<property name="hibernate.physical_naming_strategy" value="foo.bar.FooPhysicalNamingStrategy"/>

NOTE

JPA Introspection:

From Hibernate User Guide:

JPA defines no separation between logical and physical name. Following the JPA specification, the logical name is the physical name. If JPA provider portability is important, applications should prefer not to specify a PhysicalNamingStrategy.


Further Reading

Related