springboot结合flyway自动创建数据库及数据表

3,932 阅读1分钟

编写DataSource ,在程序启动的时候判断数据库是否存在,如果存在不做任何操作,如果不存在则创建数据库

    import com.alibaba.druid.pool.DruidDataSource;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    
    import javax.sql.DataSource;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    
    /**
     * Created by xjw
     */
    @Configuration
    @Primary //在同样的DataSource中,首先使用被标注的DataSource
    public class DataSourceConfig {
        private Logger log = LoggerFactory.getLogger(DataSourceConfig.class);
    
        @Value("${spring.datasource.url}")
        //jdbc:mysql://127.0.0.1:3306/insight?useUnicode=true&characterEncoding=utf8&failOverReadOnly=false&allowMultiQueries=true
        private String datasourceUrl;
        @Value("${spring.datasource.driver-class-name}")
        private String driverClassName;
        @Value("${spring.datasource.username}")
        private String username;
        @Value("${spring.datasource.password}")
        private String password;
    
        @Bean     //声明其为Bean实例
        public DataSource dataSource(){
            DruidDataSource datasource = new DruidDataSource();
    
            datasource.setUrl(datasourceUrl);
            datasource.setUsername(username);
            datasource.setPassword(password);
            datasource.setDriverClassName(driverClassName);
    
            try {
                Class.forName(driverClassName);
    
                String url01 = datasourceUrl.substring(0,datasourceUrl.indexOf("?"));
    
                String url02 = url01.substring(0,url01.lastIndexOf("/"));
    
                String datasourceName = url01.substring(url01.lastIndexOf("/")+1);
                // 连接已经存在的数据库,如:mysql
                Connection connection = DriverManager.getConnection(url02, username, password);
                Statement statement = connection.createStatement();
    
                // 创建数据库
                statement.executeUpdate("create database if not exists `" + datasourceName + "` default character set utf8 COLLATE utf8_general_ci");
    
                statement.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
    
            return datasource;
        }
    }

在springboot中引入flyway

flyway官网

  1. 在pom.xml中引入jar

     <dependency>  
         <groupId>org.flywaydb</groupId>  
         <artifactId>flyway-core</artifactId>  
     </dependency>
    
  2. 在配置文件中(application.properties )中添加配置

     flyway.baselineOnMigrate=true  
     flyway.locations=classpath:db/migration/ # sql文件的位置  
     spring.datasource.validationQuery=SELECT 1     
     
    
  3. 根据flyway.locations 配置的位置新增文件夹及文件

	其中 V 代表版本控制,1.0 1.1代表版本号
	(注:V1.0 后面是 两个 _ 否则不起作用。sql语句中不能含有创建  schema_version表的信息否则报错)
	这样就可以使用flyway控制数据库的版本了。