Create database programmatically from Spring boot application

Viewed 177

I am having a multi-tenancy application developed with Spring boot. In the master table I hold information about the tenant databases. I am trying to create a service, that receives a row from the master table and creates the database for it. Is there a known way to do this in Spring boot? The only information I can find on internet is creating at start up of the application and this is not desired. Thank you in advance! The master-tenant table is in a master schema and has the following structure: enter image description here

The method from the service is as follows:

public void createTenant(TenantDTO tenantDTO) {
    tenantepository.save(new Tenant(tenantDTO));
    MasterTenant masterTenant = new MasterTenant();
    masterTenant.setDbName(tenantDTO.getTenantId());
    masterTenant.setDriverClass("com.mysql.jdbc.Driver");
    masterTenant.setTenantId(tenantDTO.getTenantId());
    masterTenant.setPassword("password");
    masterTenant.setStatus(EStatus.ACTIVE.name());
    masterTenant.setUserName("root");
    masterTenant.setUrl("jdbc:mysql://localhost:3306/"+tenantDTO.getTenantId());
    DBContextHolder.setCurrentDb(masterTenant.getDbName());
    masterTenantRepository.save(masterTenant);
    multiTenantConnectionProvider.selectDataSource(masterTenant.getTenantId());
    //create schema + create tables from existing entities or run a script of sql 
}

I would need help figuring out the part with create schema and tables.

0 Answers
Related