Table name configured with external properties file

前端 未结 2 1907
予麋鹿
予麋鹿 2020-12-05 21:26

I build a Spring-Boot application that accesses a Database and extracts data from it. Everything is working fine, but I want to configure the table names from an external .p

相关标签:
2条回答
  • 2020-12-05 21:50

    Spring boot solution: Create below class

    @Configuration
    public class CustomPhysicalNamingStrategy extends SpringPhysicalNamingStrategy{
    
    @Value("${table.name}")
    private String tableName;
    
    @Override
    public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
        return Identifier.toIdentifier(tableName);
    }
    

    }

    Add below property to application.properties:

    spring.jpa.properties.hibernate.physical_naming_strategy=<package.name>.CustomPhysicalNamingStrategy
    table.name=product
    
    0 讨论(0)
  • 2020-12-05 21:52

    Table names are really coming from hibernate itself via its strategy interfaces. Boot configures this as SpringNamingStrategy and there were some changes in Boot 2.x how things can be customised. Worth to read gh-1525 where these changes were made. Configure Hibernate Naming Strategy has some more info.

    There were some ideas to add some custom properties to configure SpringNamingStrategy but we went with allowing easier customisation of a whole strategy beans as that allows users to to whatever they need to do.

    AFAIK, there's no direct way to do config like you asked but I'd assume that if you create your own strategy you can then auto-wire you own properties to there. As in those customised strategy interfaces you will see the entity name, you could reserve a keyspace in boot's configuration properties to this and match entity names.

    mytables.naming.fleet.name=foobar
    mytables.naming.othertable.name=xxx
    

    Your configuration properties would take mytables and within that naming would be a Map. Then in your custom strategy it would simply be by checking from mapping table if you defined a custom name.

    0 讨论(0)
提交回复
热议问题