Stack Exchange
Dynamic table name in spring boot with Jpa
My requirement:
My requirement is to read the table name from properties file.
its working fine as expected without custom database configuration.
when i declare the following way, its working fine.
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.default_schema=upload
#spring.jpa.hibernate.ddl-auto=create-drop
#sample.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect    
spring.jpa.propertie.hibernate.physical_naming_strategy=com.example.demo.entities.TableNameStrategy.

but when i do custom database configuration, i am getting the following error
Caused by: java.lang.NullPointerException: null
    at com.example.demo.entities.TableNameStrategy.toPhysicalTableName(TableNameStrategy.java:25) ~[classes/:na]
    at org.hibernate.boot.model.relational.Namespace.createTable(Namespace.java:92) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.addTable(InFlightMetadataCollectorImpl.java:772) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.cfg.annotations.TableBinder.buildAndFillTable(TableBinder.java:509) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.cfg.annotations.EntityBinder.bindTable(EntityBinder.java:848) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:647) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.processEntityHierarchies(AnnotationMetadataSourceProcessorImpl.java:250) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.processEntityHierarchies(MetadataBuildingProcess.java:231) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:274) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    ... 17 common frames omitted

Here is my custom database configuration code:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef="sampleEntityManager", 
                       transactionManagerRef="sampleTransactionManager",
                       basePackages= {"com.example.demo.repo"})
public class SampleConfiguration {


    @Autowired
    Environment env;



    @Bean(name="sampleDataSource")
    @Primary
    public DataSource dmsDataSource() { 

          DriverManagerDataSource dataSource = new DriverManagerDataSource();

          dataSource.setDriverClassName(env.getProperty("sample.datasource.driver-class-name"));
          dataSource.setUrl(env.getProperty("sample.datasource.url"));
          dataSource.setUsername(env.getProperty("sample.datasource.username"));
          dataSource.setPassword(env.getProperty("sample.datasource.password"));

        return dataSource;
    }


    @Primary
    @Bean(name = "sampleEntityManager")
    public LocalContainerEntityManagerFactoryBean dmsEntityManagerFactory(EntityManagerFactoryBuilder builder) {

        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.jdbc.lob.non_contextual_creation",env.getProperty("sample.jpa.properties.hibernate.jdbc.lob.non_contextual_creation"));
        properties.put("hibernate.default_schema", env.getProperty("sample.jpa.properties.hibernate.default_schema"));
        properties.put("hibernate.ddl-auto", env.getProperty("sample.jpa.properties.hibernate.ddl-auto"));
        properties.put("hibernate.physical_naming_strategy",env.getProperty("sample.jpa.properties.hibernate.physical_naming_strategy"));

        return builder
                    .dataSource(dmsDataSource())
                    .properties(properties)
                    .packages("com.example.demo.entities")
                    .persistenceUnit("dms")
                    .build();
    }

    @Primary
    @Bean(name = "sampleTransactionManager")
    public PlatformTransactionManager dmsTransactionManager(@Qualifier("sampleEntityManager") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

this is class where i am defining my table name:
 @Configuration 
   public class TableNameStrategy extends org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy implements Serializable {

    public static final PhysicalNamingStrategyStandardImpl INSTANCE = new PhysicalNamingStrategyStandardImpl();

    @Autowired 
    Environment env;

    @Override public Identifier toPhysicalTableName(Identifier name,JdbcEnvironment context) {
        return new Identifier(name.toIdentifier(env.getProperty("tableName")).getText(),
                        name.isQuoted());
    } 

}

My properties file:
sample.datasource.url=jdbc:postgresql://localhost:5432/postgres
sample.datasource.username=postgres
sample.datasource.password=postgres
sample.datasource.driver-class-name=org.postgresql.Driver
sample.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
sample.jpa.properties.hibernate.default_schema=upload
sample.jpa.hibernate.ddl-auto=create-drop
sample.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect 
sample.jpa.propertie.hibernate.physical_naming_strategy=com.example.demo.configuration.TableNameStrategy

tableName=dynamictable //table name

My entity Class
@Entity
@Data
public class Sample {

    @Id
    private Integer id;

}

with custom database configuration, its not working as expected. can anyone tell me where i am making mistakes?

Try making the environment variable 'private final' and set it in the constructor

it says line number 25 (TableNameStrategy.java:25)

@r33tnup  i tried in  the following way as you said private final String table;
TableNameStrategy(){
table=env.getProperty("tableName");
} but its not working

You're missing an 's' in your properties: propertie

Specified property in application.properties is not correct.
What you specified: spring.jpa.propertie.hibernate.physical_naming_strategy=com.example.demo.entities.TableNameStrategy
Correct:
spring.jpa.hibernate.naming.physical-strategy=com.example.demo.entities.TableNameStrategy
I suggest you to check argument if it is required because it can cause NullPointerException.
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
    return new Identifier(toIdentifier(getTableName()).getText(), name.isQuoted());
}

private String getTableName() {
    return environment.getRequiredProperty(PROPERTY_TABLE_NAME);
}

because Identifier.toIdentifier can return null value.
public static Identifier toIdentifier(String text) {
    if ( StringHelper.isEmpty( text ) ) {
        return null;
    }
...
}

public final class StringHelper {
...
public static boolean isEmpty(String string) {
    return string == null || string.isEmpty();
}
...


+1 fixed it for me. For the next reader: Only the part that says spring.jpa.hibernate.naming.physical-strategy=... is relevant in this answer, when you have the code of the question.
