SpringBoot项目启动自动执行sql脚本

13 篇文章 0 订阅

1. 创建SpringBoot项目(Maven)

2. 添加依赖

添加数据库驱动依赖,此处使用的是mysql数据库

<dependencies>
  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
  </dependency>
</dependencies>

3. 配置文件

编辑application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?nullNamePatternMatchesAll=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=123456

yaml格式

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?nullNamePatternMatchesAll=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT
    username: root
    password: 123456

4. 编写sql脚本文件

在resource目录下创建一个目录,创建sql文件 schema.sql 和 data.sql(可以创建多个)

schema.sql —— DDL脚本文件

SET NAMES utf8mb4; $$$
SET FOREIGN_KEY_CHECKS = 0;$$$
DROP TABLE IF EXISTS `tb_user_copy`;
CREATE TABLE `tb_user_copy`  (
  `username` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `password` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `username-unique`(`username`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户表' ROW_FORMAT = Dynamic;$$$
SET FOREIGN_KEY_CHECKS = 1;$$$

data.sql ——DQL(数据查询)脚本或DML(数据操作)脚本 文件, 一般都是数据插入脚本文件

INSERT INTO `tb_user_copy` VALUES ('test', 1, 'test123');$$$
INSERT INTO `tb_user_copy` VALUES ('test01', 2, 'test001');$$$
INSERT INTO `tb_user_copy` VALUES ('test02', 3, 'test002');$$$
INSERT INTO `tb_user_copy` VALUES ('test123', 4, 'test123');$$$
INSERT INTO `tb_user_copy` VALUES ('test1', 5, 'test001');$$$

procedure.sql—— 存储过程脚本文件

-- 当存储过程`p`存在时,删除。$$$ 为分隔符
drop procedure if exists p1;$$$

-- 创建存储过程`p`
create procedure p() 
begin
  declare row_num int;
  select count(*) into row_num from `tb_user_copy`;
  if row_num = 0 then
    INSERT INTO `tb_user_copy`(`username`, `password`) VALUES ('zhangsan', '123456');
  end if;
end;$$$

-- 调用存储过程`p`
call p();$$$
drop procedure if exists p;$$$

function.sql ——存储函数脚本文件

5. 启动执行sql脚本文件(两种方式)

方式1:在配置文件中配置相关属性

关键属性:

  • spring.datasource.schema
    表初始化语句,默认加载schema.sql,看getScripts源码,它还会加载schema-${platform}.sql文件,其中platform就是spring.datasource.platform的值
    指定DDL脚本文件

  • spring.datasource.data
    数据初始化,默认加载data.sql,还会加载data-${platform}.sql文件
    指定 DQL(数据查询)脚本或DML(数据操作)脚本 文件, 一般都是数据插入脚本文件

  • spring.datasource.platform
    为了支持不同数据库
    platform属性的默认值是’all’,所以当有在不同数据库切换的情况下才使用all配置,因为默认值的情况下,spring boot会自动检测当前使用的数据库。

  • spring.datasource.initialization-mode
    初始化模式(springboot2.0),其中有三个值:
    always为始终执行初始化
    embedded只初始化内存数据库(默认值),如h2等
    never为不执行初始化
    在SpringBoot1.x中,不需要配置便可之间运行
    在SpringBoot 2.x 版本中,默认值是embedded,所以必须配置为 always

  • spring.datasource.separator
    默认为 ;,自定义存储过程或者函数时,可能需要使用delimiter设置断句分隔符,但是delimiter在springboot执行的sql脚本里不可用。springboot提供了spring.datasource.separator配置解决这个问题,如上配置之后,不必执行delimiter $$$,我们在脚本里可以直接使用$$$作为分隔符。

    因为SpringBoot在解析sql脚本时,默认是以’;'作为断句的分隔符的。即:SpringBoot把create procedure p() begin declare row_num int当成是一条普通的sql语句。而我们需要的是创建一个存储过程。执行时会报异常Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'create procedure p() begin declare row_num int' at line 1

    因此需要在作为分隔符的; 后加上配置的分隔符 $$$

其他属性:
spring.datasouce.data-password
spring.datasouce.data-username
spring.datasouce.schema-password
spring.datasouce.schema-username
这四个值为执行schema.sql或者data.sql时,用的用户

配置文件:

  1. properties
    spring.datasource.schema=classpath:sql/schema.sql, sql/procedure.sql, sql/function.sql
    spring.datasource.data=classpath:sql/data.sql  
    spring.datasource.platform=mysql   
    spring.datasource.initialization-mode=always 
    spring.datasource.separator=$$$ 
    
  2. yaml格式:
    spring:
      datasource:
        schema: 
          - classpath:sql/schema.sql
          - classpath:sql/procedure.sql
          - classpath:sql/function.sql
        data: classpath:sql/data.sql
        initialization-mode: always
        platform: mysql
        separator: $$$ # 默认为 ;
    

方式2: 自定义DataSourceInitializer

在SpringBoot的架构中,DataSourceInitializer类可以在项目启动后初始化数据,我们可以通过自动执行自定义sql脚本初始化数据。通过自定义DataSourceInitializer Bean就可以实现按照业务要求执行特定的脚本。

package top.theonly.springboot.datasource.initializer.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;

/**
 * @ClassName CustomizeDataSourceInitializer
 * @Description: TODO
 * @Author guoshihua
 * @Date 2020/5/5 0005 下午 3:47
 * @Version V1.0
 * @See 版权声明
 **/
@Configuration
public class CustomizeDataSourceInitializer {

    @Value("classpath:sql/schema.sql")
    private Resource sqlScriptSchema;
    @Value("classpath:sql/data.sql")
    private Resource sqlScriptData;
    @Value("classpath:sql/procedure.sql")
    private Resource sqlScriptProcedure;
    @Value("classpath:sql/function.sql")
    private Resource sqlScriptFunction;
	
    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource){
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        dataSourceInitializer.setDatabasePopulator(databasePopulator());
        return dataSourceInitializer;
    }

    private DatabasePopulator databasePopulator(){
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(sqlScriptSchema);
        populator.addScript(sqlScriptData); 
        populator.addScript(sqlScriptProcedure);
        populator.addScript(sqlScriptFunction); 
        populator.setSeparator("$$$"); // 分隔符,默认为;
        return populator;
    }
}

6. 运行SpringBoot项目,查看数据库

运行项目
在这里插入图片描述
查看数据库
在这里插入图片描述

7. 不同运行环境执行不同脚本

一般情况下,都会有多个运行环境,比如开发、测试、生产等。而不同运行环境通常需要执行的sql会有所不同。为解决这个问题,可以使用通配符来实现。

创建不同环境的文件夹
在resources文件夹创建不同环境对应的文件夹,如dev/、test/、prod/。

配置
application.yml

spring:
  datasource:
    schema: classpath:${spring.profiles.active:dev}/schema.sql 
    data: classpath:${spring.profiles.active:dev}/data.sql
    initialization-mode: always
	platform: mysql
	separator: $$$ # 默认为 ;
注:\${}通配符支持缺省值。如上面的配置中的`${spring.profiles.active:dev}`,其中分号前是取属性spring.profiles.active的值,而当该属性的值不存在,则使用分号后面的值,即dev。

bootstrap.yml

spring:
  profiles:
    active: dev # dev/test/prod等。分别对应开发、测试、生产等不同运行环境。
提醒:spring.profiles.active属性一般在bootstrap.yml或bootstrap.properties中配置。
  • 11
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
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语句

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值