在Flyway执行数据库脚本之前创建数据库

Flyway让我们不用手动执行sql脚本,但是众所周知,前提是要先创建项目的数据库。为了能够让运维的同事再偷一次懒,通过代码来自动完成数据库的创建,于是有了这篇文章的分享~

要实现这个效果,只需要两步:

第一步:排除Flyway的自动配置类

在springboot启动类上的注解上添加属性exclude = {FlywayAutoConfiguration.class}

@SpringBootApplication(exclude = {FlywayAutoConfiguration.class})

例如:

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);
    }

}

第二步:手动执行Flyway的初始化方法

在调用Flyway的load()方法之前执行创建数据库的SQL语句

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();
        }
    }

}

第一次启动项目时效果(数据库还没有创建)

在Flyway执行数据库脚本之前创建数据库_第1张图片

第二次启动的效果

在Flyway执行数据库脚本之前创建数据库_第2张图片

你可能感兴趣的:(数据库)