hibernate Creating and Using a Custom ImplicitNamingStrategy


Example

Creating a custom ImplicitNamingStrategy allows you to tweak how Hibernate will assign names to non-explicitly named Entity attributes, including Foreign Keys, Unique Keys, Identifier Columns, Basic Columns, and more.

For example, by default, Hibernate will generate Foreign Keys which are hashed and look similar to:

FKe6hidh4u0qh8y1ijy59s2ee6m

While this is often not an issue, you may wish that the name was more descriptive, such as:

FK_asset_tenant

This can easily be done with a custom ImplicitNamingStrategy.

This example extends the ImplicitNamingStrategyJpaCompliantImpl, however you may choose to implement ImplicitNamingStrategy if you wish.

import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.ImplicitForeignKeyNameSource;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;

public class CustomNamingStrategy extends ImplicitNamingStrategyJpaCompliantImpl {

    @Override
    public Identifier determineForeignKeyName(ImplicitForeignKeyNameSource source) {
        return toIdentifier("FK_" + source.getTableName().getCanonicalName() + "_" + source.getReferencedTableName().getCanonicalName(), source.getBuildingContext());
    }

}

To tell Hibernate which ImplicitNamingStrategy to use, define the hibernate.implicit_naming_strategy property in your persistence.xml or hibernate.cfg.xml file as below:

<property name="hibernate.implicit_naming_strategy"
                  value="com.example.foo.bar.CustomNamingStrategy"/>

Or you can specify the property in hibernate.properties file as below:

hibernate.implicit_naming_strategy=com.example.foo.bar.CustomNamingStrategy

In this example, all Foreign Keys which do not have an explicitly defined name will now get their name from the CustomNamingStrategy.