Kirill Sukhanov
Kirill Sukhanov

Reputation: 93

Spring export schema DDL to the database in runtime

I'm using Dynamic DataSource in my Spring Boot application.

The problem is I need to generate tables from my entities. There is a way with

spring.jpa.hibernate.ddl-auto=update

but it doesn't work for me since I need to connect to Database in run-time. What I need to know is can I call some method to do same things as Spring does on application startup with mentioned option.

Upvotes: 0

Views: 763

Answers (1)

Kirill Sukhanov
Kirill Sukhanov

Reputation: 93

Okey after some research I found the answer. All you need is to ask sessionFactoryBuilder to generate update scripts for your database and execute than with JdbcTemplate.

    LocalSessionFactoryBuilder sessionFactory = new LocalSessionFactoryBuilder(dataSource);
    sessionFactory.scanPackages("su");
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    try{
        List<SchemaUpdateScript> scripts = sessionFactory.generateSchemaUpdateScriptList(new PostgreSQL9Dialect(),
                new DatabaseMetadata(dataSource.getConnection(), new PostgreSQL9Dialect(), sessionFactory));
        log.info("Schema update scripts["+scripts.size()+"]");
        for (SchemaUpdateScript script:scripts ) {
            log.info(script.getScript());
            jdbcTemplate.execute(script.getScript());
        }
    }catch (Exception e){
        log.error("error updating schema",e);
    }

Upvotes: 1

Related Questions