Home > Software engineering >  How can I apply a custom hibernate table naming strategy in Grails 5
How can I apply a custom hibernate table naming strategy in Grails 5

Time:03-16

I have a requirement to apply table prefixes to all database tables created by Gorm/Hibernate.

In previous versions of Grails, this could be achieved through the use of the 'naming_strategy' property in the hibernate config and by using a custom class. With Hibernate5 this no longer works and any custom naming class appears to be completely ignored.

I have attempted to instantiate and set such classes through application.yml, application.groovy, even environment properties as all these approaches will work in pure Spring Boot, however Grails seems to be overriding whatever settings I have specified.

Has anyone faced the same issue and discovered how to achieve this ?

A simple example of my custom class is as follows:

class CustomNamingStrategy extends PhysicalNamingStrategyStandardImpl  {

  @Override
  Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
    return "customprefix_"   name
  }

}

And examples of specifying the naming strategy:

spring:
  jpa:
    properties:
      hibernate:
        physical_naming_strategy: tableprefix.CustomNamingStrategy
    hibernate:
      naming:
        physical-strategy: tableprefix.CustomNamingStrategy
        physical_naming_strategy: tableprefix.CustomNamingStrategy
hibernate:
  physical_naming_strategy: tableprefix.CustomNamingStrategy

I have a single domain, Customer, and in each case, the created table name is always 'customer', not 'customprefix_customer' which is what I'm attempting to achieve.

CodePudding user response:

The answer in my particular situation was in the way the custom strategy class was declared.

In v2, in config.groovy the naming strategy was instantiating a new class, making use of it's constructor i.e.

naming_strategy = new myPackage.MyCustomStrategy('table_prefix')

This allowed different table prefixes to be used in different 'environment' blocks.

It appears that this is no longer permitted, you have to specify the class name alone... i.e. this is what now works...

naming_strategy = myPackage.MyCustomStrategy

With this methodology, however, you can't use the constructor to pass in any value, so in my case, I am setting an additional variable in the config to state the table prefix, and within the MyCustomStrategy class, I am reading in the config value.

Problem solved.. BUT for how long I'm not sure as mentioned previously, this naming_strategy strategy is deprecated and Hibernate suggests it should be replaced by PhysicalNamingStrategy and ImplicitNamingStrategy, hopefully the Grails team will allow these to be specified in an upcoming release.

  • Related