package com.glxp.api.config; import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.io.IoUtil; import cn.hutool.core.lang.UUID; import com.glxp.api.dao.system.DbVersionDao; import com.glxp.api.entity.system.DbVersionEntity; import com.glxp.api.entity.system.SchemaData; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; @Order(1) @Component @Slf4j public class HdSchemaExecutor implements ApplicationRunner { @Resource DbVersionDao hdCommonDao; private List schema = new ArrayList<>(); @Override public void run(ApplicationArguments args) throws Exception { //初始版本列表 buildSchemas(); //定义sql文件路径 String basePath = "schemas/"; //非版本控制,初始化脚本 ClassLoader loader = this.getClass().getClassLoader(); //通过流的方式获取项目路径下的文件 InputStream inputStream = loader.getResourceAsStream(basePath + "init.sql"); //获取文件内容 String sql = IoUtil.readUtf8(inputStream); try { //判断版本表是否存在 int count = hdCommonDao.selectTableExist("hd_version"); if (count == 0) { hdCommonDao.updateSql(sql); } for (SchemaData schemaData : schema) { //查询版本记录是否存在 count = hdCommonDao.selectVersion(schemaData.getVersion()); if (count == 0) { log.info("--------------执行数据脚本,版本:" + schemaData.getVersion()); //获取对应sql脚本 inputStream = loader.getResourceAsStream(basePath + schemaData.getFileName()); sql = IoUtil.readUtf8(inputStream); hdCommonDao.updateSql(sql); DbVersionEntity entity = new DbVersionEntity(); entity.setId(UUID.randomUUID().toString()); entity.setVersion(schemaData.getVersion()); entity.setCreated(new Date()); entity.setRemark(schemaData.getFileName()); //写入版本记录 hdCommonDao.insertVersion(entity); } } } catch (IORuntimeException e) { e.printStackTrace(); } finally { //关闭流 inputStream.close(); } } public void buildSchemas() { // schema.add(new SchemaData("v2.1", "schema_v2.1.sql")); schema.add(new SchemaData("v2.2", "schema_v2.2.sql")); } }