SpringBoot启动时自动执行sql脚本

一、通过配置

需要配置项目下的yml文件:
在文件下加如如下配置:

    data: classpath:code-generator-data.sql
    initialization-mode: always

spring.datasource.initialization-mode:
初始化模式(springboot2.0),其中有三个值:
always为始终执行初始化
embedded只初始化内存数据库(默认值),如h2等
never为不执行初始化

spring.datasource.data:
数据初始化,默认加载data.sql,还会加载data-${platform}.sql文件,也可以指定文件,一般放在resources文件夹下,然后使用classpath:文件.sql
指定 DQL(数据查询)脚本或DML(数据操作)脚本 文件, 一般都是数据插入脚本文件

yml:

spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/are_code_generator
    username: postgres
    password: 123456
    data: classpath:code-generator-data.sql
    initialization-mode: always
  #    url: jdbc:mysql://192.168.70.38:4307/are_oms_tankInfo?useUnicode=true&characterEncoding=utf-8&useSSL=false
  #    username: root
  #    password: 123456
  jackson:
    time-zone: GMT+8
  jpa:
    properties:
      open-in-view: true
      hibernate:
        show_sql: true
        format_sql: true
        dialect: org.hibernate.dialect.PostgreSQLDialect
        temp:
          use_jdbc_metadata_defaults: false
        hbm2ddl:
          auto: update
    database: postgresql
  rabbitmq:
    host: 192.168.90.230
    port: 5672
    username: vxsip
    password: vxsip
    virtual-host: /
service:
  employee:
    staff: http://192.168.90.230/msc/are-basic/v1/sys/organization/staffs
    moudleAccountUrl: http://192.168.90.230/msc/are-basic/v1/login/account

二、通过代码加载sql
首先将sql文件放在根目录下,将文件加载:

  @Value("classpath:create_table.sql")
    private Resource createTableSql;

重写数据源初始化方法:

@Bean
    public DataSourceInitializer dataSourceInitializer(final @Qualifier("forwardDataSource") DataSource dataSource) {
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        dataSourceInitializer.setDatabasePopulator(databasePopulator());
        return dataSourceInitializer;
    }

    private DatabasePopulator databasePopulator() {
        ResourceDatabasePopulator populate = new ResourceDatabasePopulator();
        populate.addScript(createTableSql);
        return populate;
    }
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、付费专栏及课程。

余额充值