Create database before Flyway executes database script

Flyway saves us from manually executing sql scripts, but as we all know, the prerequisite is to create the project's database first. In order to allow the operation and maintenance colleagues to be lazy again and automatically create the database through code, I shared this article~

To achieve this effect, only two steps are needed:

Step 1: Exclude Flyway’s automatic configuration class

Add the attribute exclude = {FlywayAutoConfiguration.class} to the annotation on the springboot startup class

@SpringBootApplication(exclude = {FlywayAutoConfiguration.class})

For example:

package cn.edu.sgu.www.mhxysy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @author heyunlin
 * @version 1.0
 */
@EnableFeignClients(basePackages = "cn.edu.sgu.www.mhxysy.feign")
@SpringBootApplication(exclude = {FlywayAutoConfiguration.class})
public class MhxysyManagement {

    static Logger logger = LoggerFactory.getLogger(MhxysyManagement.class);

    public static void main(String[] args) {
        if (logger.isDebugEnabled()) {
            logger.debug("启动梦幻西游手游管理系统...");
        }

        SpringApplication.run(MhxysyManagement.class, args);
    }

}

Step 2: Manually execute Flyway’s initialization method

Execute the SQL statement that creates the database before calling Flyway's load() method.

package cn.edu.sgu.www.mhxysy.config;

import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayProperties;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * flyway配置类
 * @author heyunlin
 * @version 1.0
 */
@Slf4j
@Configuration
public class FlywayConfig {

    private final DataSource dataSource;
    private final DataSourceProperties dataSourceProperties;

    @Autowired
    public FlywayConfig(DataSource dataSource, DataSourceProperties dataSourceProperties) {
        this.dataSource = dataSource;
        this.dataSourceProperties = dataSourceProperties;
    }

    @Bean
    public FlywayProperties flywayProperties() {
        return new FlywayProperties();
    }

    @PostConstruct
    public void migrate() throws SQLException {
        String username = dataSourceProperties.getUsername();
        String password = dataSourceProperties.getPassword();
        String url = dataSourceProperties.getUrl();

        // MySQL数据库连接的url
        String connectUrl = url.substring(0, url.lastIndexOf("/"));
        // 数据库名
        String database = url.substring(url.lastIndexOf("/") + 1);
        // 创建数据库的SQL
        String sql = "create database if not exists " + database + " DEFAULT CHARSET utf8mb4";

        // 创建数据库连接
        Connection connection = DriverManager.getConnection(connectUrl, username, password);
        PreparedStatement statement = connection.prepareStatement(sql);

        int update = statement.executeUpdate();

        if (update > 0) {
            log.debug("数据库{}不存在,已经完成创建...", database);
        }

        FlywayProperties flywayProperties = flywayProperties();

        if (flywayProperties.isEnabled()) {
            log.debug("FlywayConfig.migrate()方法执行...");

            Flyway flyway = Flyway.configure()
                    .dataSource(dataSource)
                    .locations(flywayProperties.getLocations().toArray(new String[]{}))
                    .baselineOnMigrate(flywayProperties.isBaselineOnMigrate())
                    .load();

            flyway.migrate();
        }
    }

}

Effect when starting the project for the first time (the database has not been created yet)

The effect of the second startup

Guess you like

Origin blog.csdn.net/heyl163_/article/details/135426583