赞
踩
Spring boot项目启动后没有该数据库则先创建数据库然后执行flyway脚本创建相应表数据,其中可能存在bean加载顺序问题,比如我的安全框架会先去加载我的resouece表,但是flyway在其后面执行,所以我们需要自定义bean加载顺序,即先创建数据库-》加载flyway配置-》其他调用表数据资源配置。
- <!--flywaydb-->
- <dependency>
- <groupId>org.flywaydb</groupId>
- <artifactId>flyway-core</artifactId>
- <version>5.2.4</version>
- </dependency>
- spring:
- application:
- name: sims
- datasource:
- url: jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
- username: root
- password: root
- driver-class-name: com.mysql.cj.jdbc.Driver
- flyway:
- #开启
- enabled: true
- #当迁移时发现目标schema非空,而且带有没有元数据的表时,是否自动执行基准迁移,默认false.
- baseline-on-migrate: true
- # 检测迁移脚本的路径是否存在,如不存在,则抛出异常
- check-location: true
- #sql脚本位置
- locations: classpath:db/migration
- #是否允许无序的迁移,默认false
- out-of-order: false
- #编码
- encoding: UTF-8
- # flyway.baseline-description对执行迁移时基准版本的描述.
- # flyway.baseline-on-migrate当迁移时发现目标schema非空,而且带有没有元数据的表时,是否自动执行基准迁移,默认false.
- # flyway.baseline-version开始执行基准迁移时对现有的schema的版本打标签,默认值为1.
- # flyway.check-location检查迁移脚本的位置是否存在,默认false.
- # flyway.clean-on-validation-error当发现校验错误时是否自动调用clean,默认false.
- # flyway.enabled是否开启flywary,默认true.
- # flyway.encoding设置迁移时的编码,默认UTF-8.
- # flyway.ignore-failed-future-migration当读取元数据表时是否忽略错误的迁移,默认false.
- # flyway.init-sqls当初始化好连接时要执行的SQL.
- # flyway.locations迁移脚本的位置,默认db/migration.
- # flyway.out-of-order是否允许无序的迁移,默认false.
- # flyway.password目标数据库的密码.
- # flyway.placeholder-prefix设置每个placeholder的前缀,默认${.
- # flyway.placeholder-replacementplaceholders是否要被替换,默认true.
- # flyway.placeholder-suffix设置每个placeholder的后缀,默认}.
- # flyway.placeholders.[placeholder name]设置placeholder的value
- # flyway.schemas设定需要flywary迁移的schema,大小写敏感,默认为连接默认的schema.
- # flyway.sql-migration-prefix迁移文件的前缀,默认为V.
- # flyway.sql-migration-separator迁移脚本的文件名分隔符,默认__
- # flyway.sql-migration-suffix迁移脚本的后缀,默认为.sql
- # flyway.tableflyway使用的元数据表名,默认为schema_version
- # flyway.target迁移时使用的目标版本,默认为latest version
- # flyway.url迁移时使用的JDBC URL,如果没有指定的话,将使用配置的主数据源
- # flyway.user迁移数据库的用户名
- # flyway.validate-on-migrate迁移时是否校验,默认为true.
这里是我们要执行的脚本,命名要符合规范,开头V与R区别自己可以去flyway官网查看。
- @SpringBootApplication(exclude = {FlywayAutoConfiguration.class})
- @EnableTransactionManagement
- public class TestApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(TestApplication.class, args);
- }
- }
- import com.alibaba.druid.pool.DruidDataSource;
- import org.common.enums.SystemConstant;
- 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;
-
-
- @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 datasourceName = url01.substring(url01.lastIndexOf("/")+1);
- // 可以定义一个常量或者自行切割url01,切割时mysql8会存在一个时区设置问题
- // url02切割后应该形如:"jdbc:mysql://127.0.0.1:3306?serverTimezone=UTC"的字符串
- String url02 = SystemConstant.MYSQL_CONNECTION;
- // 连接已经存在的数据库,如: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;
- }
- }
- import javax.annotation.PostConstruct;
- import javax.sql.DataSource;
- import org.flywaydb.core.Flyway;
- import org.flywaydb.core.api.FlywayException;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- @Configuration
- public class FlywayConfig {
- @Autowired
- private DataSource dataSource;
-
- private Logger logger = LoggerFactory.getLogger(this.getClass());
-
-
- @PostConstruct
- public void migrate() {
- Flyway flyway = new Flyway();
-
- flyway.setDataSource(dataSource);
-
- // 设置flyway扫描sql升级脚本、java升级脚本的目录路径或包路径(表示是src/main/resources/flyway下面,前缀默认为src/main/resources,因为这个路径默认在classpath下面)
- flyway.setLocations("db/migration");
- // 设置sql脚本文件的编码
- flyway.setEncoding("UTF-8");
-
- flyway.setOutOfOrder(true);
-
- try {
- flyway.migrate();
- } catch (FlywayException e) {
- flyway.repair();
- logger.error("Flyway配置加载出错",e);
- }
- }
- }
-
-
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.annotation.DependsOn;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
-
- @Configuration
- @DependsOn("flywayConfig")
- public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。