編寫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
-
在pom.xml中引入jar
<dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> </dependency> 複製程式碼
-
在配置檔案中(application.properties )中新增配置
flyway.baselineOnMigrate=true flyway.locations=classpath:db/migration/ # sql檔案的位置 spring.datasource.validationQuery=SELECT 1 複製程式碼
-
根據flyway.locations 配置的位置新增資料夾及檔案
其中 V 代表版本控制,1.0 1.1代表版本號
(注:V1.0 後面是 兩個 _ 否則不起作用。sql語句中不能含有建立 schema_version表的資訊否則報錯)
這樣就可以使用flyway控制資料庫的版本了。複製程式碼