SamwellTarly
SamwellTarly

Reputation: 832

How to run DDL after Spring auto create db?

My question is simple. How to run any DDL statements after Spring's automatic schema creation?

I have set the following in my application-test.properties to auto create the database schema from the entity Java classes.

spring.jpa.hibernate.ddl-auto=create-drop

I'd like to change the data type of one column in one table after the schema is auto created.

I tried having a schema.sql file in the classpath, but that didn't help.

Any help please.

Upvotes: 1

Views: 1032

Answers (1)

Gaurao Burghate
Gaurao Burghate

Reputation: 307

Scripts which you specify in script will run before it create database. So when you fire Alter table command, you will get Table not found kind of error. What I would suggest is to create database via SQL file only and set spring.jpa.hibernate.ddl-auto=none so system wont create auto database.

Now to make your SQL file run, You can create the schema and initialize it based on the platform. Platform value is of spring.datasource.platform. Now you can create files schema-${platform}.sql and data-${platform}.sql which is processed by Spring Boot. It allows you to choose the database specific scripts if necessary. You can choose the vendor name of database(platform) like hsqldb, h2, oracle, mysql, postgresql, and so on.

I have tested with postgres and It worked for me. Sql file name was schema-postgres.sql Set below properties in application.properties file

    spring.jpa.database=POSTGRESQL
    spring.datasource.platform=postgres
    spring.datasource.url=jdbc:postgresql://localhost:5432/poc
    spring.datasource.username=postgres
    spring.datasource.password=postgres
    spring.jpa.hibernate.ddl-auto=none
    spring.datasource.initialization-mode=always

Upvotes: 2

Related Questions