springboot中执行sql文件

在springboot中添加配置执行sql文件

mode:属性有三个,always是每次启动都会执行,never是不执行,embedded还没搞明白啥意思 

# schema.sql中一般存放的是建表语句DDL
spring.datasource.schema = classpath:/sql/xxx-schema.sql
# data.sql中一般存放的是需要插入更新等sql语句DML
spring.datasource.data =  classpath:/sql/xxx-data.sql
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值