SpringBoot启动后执行sql脚本初始化数据库

实现ApplicationRunner接口可以实现SpringBoot启动成功后执行一段代码的操作

其中@Order注解用来控制配置类的加载顺序,数字越小越先加载

package com.bw.note.config.runner;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

@Component
@Order(value = 2)
public class SqlApplicationRunner implements ApplicationRunner {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SqlApplicationRunner.class);

    private static String url;

    private static String userName;

    private static String userPassword;

    @Value("${spring.datasource.url}")
    public void setUrl(String url) {
        this.url = url;
    }

    @Value("${spring.datasource.username}")
    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Value("${spring.datasource.password}")
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        LOGGER.info("=============开始执行sql脚本=============");
        try {
            /*//从class目录下直接读取
            cn.hutool.core.io.resource.Resource classPathResource = new ClassPathResource("test.sql");
            ScriptUtils.executeSqlScript(dataSource.getConnection(), (org.springframework.core.io.Resource) classPathResource);*/

            Connection conn = getOracleConnection();
            ScriptRunner runner = new ScriptRunner(conn);
            Resources.setCharset(Charset.forName("UTF-8")); //设置字符集,不然中文乱码插入错误
            runner.setLogWriter(null);//设置是否输出日志
            List<File> varList = getFiles("/home/java/sqls");
            for (File file : varList) {
                // 绝对路径读取
                Reader read = new FileReader(file);
                //从class目录下直接读取
//                Reader read = Resources.getResourceAsReader("test.sql");
                runner.runScript(read);
            }
            runner.closeConnection();
            conn.close();
            LOGGER.info("=============初始化sql脚本数据到数据库完成=============");
        } catch (Exception e) {
            LOGGER.error("初始化时sql脚本数据到数据库", e);
            LOGGER.error("=============初始化sql脚本数据到数据库失败!!!=============");
        }
    }

    /**
     * 获取数据库连接
     * @return
     * @throws Exception
     */
    public static Connection getOracleConnection() throws Exception {
        Class.forName("oracle.jdbc.OracleDriver");
        return DriverManager.getConnection(url, userName, userPassword);
    }

    /**
     * @Description:获取某个目录下所有直接下级文件,不包括目录下的子目录的下的文件,所以不用递归获取
     * @param path
     * @return
     */
    public static List<File> getFiles(String path) {
        List<File> files = new ArrayList<>();
        File file = new File(path);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i]);
                //文件名,不包含路径
                //String fileName = tempList[i].getName();
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了,
            }
        }
        return files;
    }
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值