2

I'm looking for a way to programmatically create a database in Spring Boot then put it as an active data source.

Is such a thing even possible? I see all this dynamic changing of the DBs, but that's not what I need and I can't find any information on this in the documentation, only about migrations, DB initialization etc.

Using spring boot 1.3.1 with PostgreSQL 9.4 DB.

1
  • By programmatically you mean create it at application startup? Commented Nov 23, 2016 at 9:38

2 Answers 2

1

You could execute the sql statement to create a database:

 CREATE DATABASE name;

or in the case you need the database owns to a user:

 CREATE DATABASE name OWNER username TABLESPACE tablespacename;

Then use AbstractRoutingDataSource to add the new datasource and change it to it.

Sign up to request clarification or add additional context in comments.

2 Comments

I'll have to try this out, didn't occur to me that I could have a migration with CREATE DATABASE :).
I managed to do it sort of like this. We're using Flyway in our project, so I could run statements in Flyway Callbacks, then switch my DataSource from there as well (no need for AbstractRoutingDataSource). Thanks for the idea!
1

Spring boot allows you to keep sql files in class path.These files are used to created Database initialization. you can use it from here Spring Boot Doc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.