Ask Your Question
4

How to prevent the creation of duplicate tables in h2 when using Spring and Liquibase?

asked 2023-03-20 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-02-13 13:00:00 +0000

scrum gravatar image

To prevent the creation of duplicate tables in h2 when using Spring and Liquibase, you can follow these steps:

  1. Define a unique context for your Liquibase scripts in your application.properties or application.yml file. For example:

    spring.liquibase.contexts=production
    
  2. Use the same context in your Liquibase changelog file. For example:

    <changeSet id="1" author="johndoe" context="production">
     <createTable tableName="my_table">
       ...
     </createTable>
    </changeSet>
    
  3. 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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-03-20 11:00:00 +0000

Seen: 8 times

Last updated: Feb 13 '22