- 创建需要执行的sql脚本:schema-useDrug.sql
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `chronic_use_drug_cycle_unit`;
CREATE TABLE `chronic_use_drug_cycle_unit` (
`id` varchar(21) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '主键',
`unit` varchar(8) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '单位',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '用药方案之用药周期单位表' ROW_FORMAT = Dynamic;
INSERT INTO `chronic_use_drug_cycle_unit` VALUES ('1', '1');
INSERT INTO `chronic_use_drug_cycle_unit` VALUES ('2', '2');
INSERT INTO `chronic_use_drug_cycle_unit` VALUES ('3', '3');
SET FOREIGN_KEY_CHECKS = 1;
- 将上面的sql文件放到项目的resources目录下
- 新增springboot启动监听类,该类必须实现CommandLineRunner接口,在run方法中添加sql脚本执行的方法,该类必须注册到spring容器中,然后启动springboot启动类即可完成sql脚本的初始化操作
package com.yf.usercenter.runner;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class CommandLineStartupRunner implements CommandLineRunner {
@Autowired
DataSource dataSource;
@Override
public void run(String... args) throws Exception {
log.info("执行sql建表语句");
Resource resources = new ClassPathResource("schema-useDrug.sql");
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScripts(resources);
resourceDatabasePopulator.execute(dataSource);
log.info("建表语句执行完成");
}
}