springboot启动执行sql脚本

2022-08-17 11:16:30
  1. 创建需要执行的sql脚本:schema-useDrug.sql
SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for chronic_use_drug_cycle_unit-- ----------------------------DROPTABLEIFEXISTS`chronic_use_drug_cycle_unit`;CREATETABLE`chronic_use_drug_cycle_unit`(`id`varchar(21)CHARACTERSET utf8mb4COLLATE utf8mb4_0900_ai_ciNOTNULLCOMMENT'主键',`unit`varchar(8)CHARACTERSET utf8mb4COLLATE utf8mb4_0900_ai_ciNULLDEFAULTNULLCOMMENT'单位',PRIMARYKEY(`id`)USINGBTREE)ENGINE=InnoDBCHARACTERSET= utf8mb4COLLATE= utf8mb4_0900_ai_ciCOMMENT='用药方案之用药周期单位表' ROW_FORMAT= Dynamic;-- ------------------------------ Records of chronic_use_drug_cycle_unit-- ----------------------------INSERTINTO`chronic_use_drug_cycle_unit`VALUES('1','1');INSERTINTO`chronic_use_drug_cycle_unit`VALUES('2','2');INSERTINTO`chronic_use_drug_cycle_unit`VALUES('3','3');SET FOREIGN_KEY_CHECKS=1;
  1. 将上面的sql文件放到项目的resources目录下
  2. 新增springboot启动监听类,该类必须实现CommandLineRunner接口,在run方法中添加sql脚本执行的方法,该类必须注册到spring容器中,然后启动springboot启动类即可完成sql脚本的初始化操作
packagecom.yf.usercenter.runner;importjavax.sql.DataSource;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.CommandLineRunner;importorg.springframework.core.io.ClassPathResource;importorg.springframework.core.io.Resource;importorg.springframework.jdbc.datasource.init.ResourceDatabasePopulator;importorg.springframework.stereotype.Component;/**
 * @author yangfeng
 * @version 1.0
 * @date 2022-05-27 11:30
 */@Component@Slf4jpublicclassCommandLineStartupRunnerimplementsCommandLineRunner{@AutowiredDataSource dataSource;@Overridepublicvoidrun(String... args)throwsException{//    PlanStartThread pt = new PlanStartThread();//    new Thread(pt).start();
    log.info("执行sql建表语句");Resource resources=newClassPathResource("schema-useDrug.sql");ResourceDatabasePopulator resourceDatabasePopulator=newResourceDatabasePopulator();
    resourceDatabasePopulator.addScripts(resources);
    resourceDatabasePopulator.execute(dataSource);
    log.info("建表语句执行完成");}}
  • 作者:玄妙之门
  • 原文链接:https://blog.csdn.net/yangfenggh/article/details/125007059
    更新时间:2022-08-17 11:16:30