springboot中项目启动后自动执行sql脚本

springboot中项目启动后自动执行sql脚本

背景

提供一个可以自动执行sql脚本的工具类,放在项目中,可以用于初始化sql脚本,支持dm,mysql等各种数据库,只要你的数据库连接正常。

注意事项

不同数据库中的语句分隔符不一样,如果sql脚本在数据库客户端能够执行,在脚本中不能执行,很有可能是分隔符的问题。

使用说明

sql脚本位置:resources/init/dm/init.sql;resources/init/mysql/init.sql

配置参数

db:
  init:
    db-type: dm  ## dm,mysql
    enabled: true  ## 是否启用初始化脚本
    file-names: init.sql,init_function.sql ## 初始化脚本文件名,多个文件名用逗号分隔

具体代码

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * @author zhuxuanyong
 * @date 2024/01/31
 * 自动初始化sql脚本
 */
@Data
@Component
public class InitSqlConfig implements InitializingBean {

    @Value("${db.init.enabled:false}")
    private boolean enabled;

    @Value("${db.init.db-type}")
    private String dbType;

    @Value("${db.init.file-names}")
    private String fileNames;

    @Autowired
    private DataSource dataSource;

    @Override
    public void afterPropertiesSet() {
        if (enabled && StrUtil.isNotEmpty(dbType) && StrUtil.isNotEmpty(fileNames)) {
            String[] split = fileNames.split(",");
            for (String fileName : split) {
                String sqlPath = "init/" + dbType + "/" + fileName;
                if (fileName.contains("function")) {
                    this.initFunctionSql(sqlPath);
                } else {
                    this.initSql(sqlPath);
                }
            }
        }
    }

    private void initSql(String sqlPath) {
        System.out.println("---------->初始化脚本,开始执行-->" + sqlPath);
        try {
            Connection conn = DataSourceUtils.getConnection(dataSource);
            ClassPathResource resource = new ClassPathResource(sqlPath);
            EncodedResource er = new EncodedResource(resource, "utf-8");
            ScriptUtils.executeSqlScript(conn, er);
            System.out.println("---------->初始化脚本,执行完成-->" + sqlPath);
        } catch (Exception e) {
            System.out.println("---------->初始化脚本,执行失败-->" + sqlPath + "\n" + e);
        }
    }


    private void initFunctionSql(String sqlPath) {
        System.out.println("---------->初始化脚本,开始执行-->" + sqlPath);
        try {
            Connection conn = DataSourceUtils.getConnection(dataSource);
            ClassPathResource resource = new ClassPathResource(sqlPath);
            EncodedResource er = new EncodedResource(resource, "utf-8");
            ScriptUtils.executeSqlScript(conn, er, false, false, "--", ";/", "/*", "*/");
            System.out.println("---------->初始化脚本,执行完成-->" + sqlPath);
        } catch (Exception e) {
            System.out.println("---------->初始化脚本,执行失败-->" + sqlPath + "\n" + e);
        }
    }
}

联系作者

如果有任何疑问,请邮件联系作者。
zhuxuanyong@163.com

  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
SpringBoot,可以使用MyBatis的MapperScannerConfigurer来执行SQL文件。下面是一个示例配置: 1. 在pom.xml文件添加MyBatis和MySQL的依赖: ```xml <dependencies> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> </dependencies> ``` 2. 创建一个SQL脚本文件,例如`init.sql`,并将需要执行SQL语句写入该文件。 3. 在`application.properties`或`application.yml`配置文件添加以下配置: ```properties # MyBatis mybatis.mapper-locations=classpath:mapper/*.xml # SQL脚本 spring.datasource.schema=classpath:init.sql spring.datasource.initialization-mode=always ``` 或者 ```yaml # MyBatis mybatis: mapper-locations: classpath:mapper/*.xml # SQL脚本 spring: datasource: schema: classpath:init.sql initialization-mode: always ``` 4. 创建一个实现了`ApplicationRunner`接口的类,例如`SqlRunner`,并在`run`方法执行SQL脚本: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.stream.Collectors; @Component public class SqlRunner implements ApplicationRunner { @Autowired private JdbcTemplate jdbcTemplate; @Override public void run(ApplicationArguments args) throws Exception { executeSqlScript("init.sql"); } private void executeSqlScript(String scriptPath) throws IOException { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources("classpath:" + scriptPath); for (Resource resource : resources) { String sql = new BufferedReader(new InputStreamReader(resource.getInputStream())) .lines().collect(Collectors.joining("\n")); jdbcTemplate.execute(sql); } } } ``` 这样,在SpringBoot启动时,会自动执行`init.sql`SQL语句。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

siihmc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值