To prevent the creation of duplicate tables in h2 when using Spring and Liquibase, you can follow these steps:
Define a unique context for your Liquibase scripts in your application.properties or application.yml file. For example:
spring.liquibase.contexts=production
Use the same context in your Liquibase changelog file. For example:
<changeSet id="1" author="johndoe" context="production">
<createTable tableName="my_table">
...
</createTable>
</changeSet>
Make sure that the Liquibase script is only executed once during application startup. You can do this by configuring the Liquibase bean to run only during the first run of the application:
@Bean
public SpringLiquibase liquibase(DataSource dataSource) {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setDataSource(dataSource);
liquibase.setChangeLog("classpath:liquibase-changelog.xml");
liquibase.setContexts("production");
// Only run Liquibase once during application startup
liquibase.setShouldRun(!dataSource.getConnection().getMetaData().getTables(null, null, "my_table", null).next());
return liquibase;
}
In this example, the getTables
method is used to check if the my_table
table already exists in the database. If it does, Liquibase will not run the script again.
By following these steps, you can ensure that Liquibase only creates tables once and prevents the creation of duplicate tables.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-03-20 11:00:00 +0000
Seen: 8 times
Last updated: Feb 13 '22