平時在用SpringBoot開發時我們需用連接數據庫,首先我們都是先創好數據庫名和表結構,然后在YML配置好數據庫名,這樣十分的不方便,有沒有一種方式在SpringBoot啟動時就把庫表創建好呢?
今天為大家介紹一種方式:
1.先創建數據庫,自定義一個配置類(DataSourceConfig),里面獲取YML里面的數據庫配置信息,然后通過Druid連接數據庫,運行建庫語句
@Configuration
@Primary //在同樣的DataSource中,首先使用被標注的DataSource
public class DataSourceConfig {
private Logger log = LoggerFactory.getLogger(DataSourceConfig.class);
/**jdbc:mysql://127.0.0.1:3306/insight?useUnicode=true&characterEncoding=utf8&failOverReadOnly=false&allowMultiQueries=true
*/
@Value("${spring.datasource.url}")
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;
}
}
2.建表結構,在yml里面加入如下配置就可以實現自動創建表結構
#自動運行表結構文件
spring:
datasource:
sql-script-encoding: utf-8
schema: classpath:sql/table.sql
initialization-mode: always
platform: mysql
url: jdbc:mysql://localhost:3306/move_task?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false
driverClassName: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
username: root
password: ******
3.table.sql文件內容
CREATE TABLE IF NOT EXISTS `agv_task_queue`
(
`auto_id` bigint NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
`task_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '任務id',
`node_num` int NOT NULL COMMENT '排序標識',
`exec_status` int DEFAULT NULL COMMENT '執行狀態',
PRIMARY KEY (`auto_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_general_ci;
4.測試。
啟動項目,就能看到創建好的庫和表