How to create a schema and initialize database in a Spring Boot application

Sitewide-10usd300x250 A common way to auto-create a database schema in a Spring Boot JPA application is just to set a spring.jpa.hibernate.ddl-auto property to create, create-drop or update. This would create a schema matching the entity classes in your application, when your application starts.

But, sometimes you may like to create a schema for which you have not defined entity classes. For example, if you are coding an authorization server by using spring-security-oauth2, you may like to create a schema like this.

Spring Boot provides an easy way to do so! If you place files named schema.sql and data.sql in classpath root (i.e. src/main/resurces), they’ll be run when your application starts.

It’s a powerful feature – for example, you can have different initialization scripts for different database providers. Visit Spring Boot reference for more details.

Happy coding!

2 thoughts on “How to create a schema and initialize database in a Spring Boot application

  1. Sanjay Post authorReply

    I think by multiple schema you mean a kind of multiple databases? And, you want to map an entity class to a particular database, let’s say? Interesting, but I haven’t tried or thought about this. Once you find a way, please share!

  2. Babafemi Reply

    Dear Sir,
    Thank you for the nice write up. However, the issue is I want to use multiple schemas in one application and I can get the application to route the entity classes/definitions to desired or selected schema.

    Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *