Liquibase is a great DB migration tool that have been around for a while and is stable to use in production systems.
An convenient way of running Liquibase in Spring application start Liquibase via Spring – when the application starts the Liquibase runs automatically and updates the database when needed.
This is a code snippet that:
- Setting up an Spring Java Config file
- Expects that there are a Spring wired DataSource available
- Reads the Liquibase changelog.xml file from classpath
- Adds contexts that can be used inside the change log for different profiles
- Initiates and creates a SpringLiquibase instance
- Settings the log level to verbose
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import liquibase.integration.spring.SpringLiquibase; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.Assert; @Configuration public class LiquibaseConfig { @Autowired private DataSource dataSource; @Autowired private ResourceLoader resourceLoader; @Bean public SpringLiquibase liquibase() { // Locate change log file String changelogFile = "classpath:/liquibase/changelog.xml"; Resource resource = resourceLoader.getResource(changelogFile); Assert.state(resource.exists(), "Unable to find file: " + changelogFile); // Configure Liquibase SpringLiquibase liquibase = new SpringLiquibase(); liquibase.setChangeLog(changelogFile); liquibase.setContexts("test,dev,prod"); liquibase.setDataSource(dataSource); liquibase.setDefaultSchema("mySchema"); liquibase.setDropFirst(false); liquibase.setShouldRun(true); // Verbose logging Map<String, String> params = new HashMap<>(); params.put("verbose", true); liquibase.setChangeLogParameters(params); return liquibase; } } |