Spring boot 初始化数据库

缘起

最近在用 spring boot 搞单元测试时候需要在测试初始时重建数据库表结构以及载入一些测试数据,本来打算自己写个初始化 SQL 的方法,结果发现 spring boot 自身已经提供了此功能。

实现

具体实现可参考 org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer,里面有两个方法 createSchemainitSchema

前者可以用来执行 ddl 脚本重建数据库表结构,后者可以用来初始化一些测试数据,其实二者的实现是基本一样的,这点区别算是语义上的。

随便贴点源码基本就明白了:

	public boolean createSchema() {
		List<Resource> scripts = getScripts("spring.datasource.schema",
				this.properties.getSchema(), "schema");
		if (!scripts.isEmpty()) {
			if (!isEnabled()) {
				logger.debug("Initialization disabled (not running DDL scripts)");
				return false;
			}
			String username = this.properties.getSchemaUsername();
			String password = this.properties.getSchemaPassword();
			runScripts(scripts, username, password);
		}
		return !scripts.isEmpty();
	}

原理很简单,在配置文件中配置 schemadata 指向相应的 SQL 文件即可,例如 application.yml

spring:
    profiles:
        active: test

    output.ansi.enabled: ALWAYS

    datasource:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/xxx
        username: root
        password: root

        initialization-mode: always
        schema:
            - classpath*:table-drop-ddl.sql
            - classpath*:table-create-ddl.sql

重点是下面几行,initialization-mode 参见 org.springframework.boot.jdbc.DataSourceInitializationMode,因为用了第三方连接池,所以这儿需要使用 always

schema 则是指向的初始化 SQL 脚本位置,我这儿是分为两个,一个用来删除表,一个用来创建表。

如果需要初始化数据,则可以使用 data,具体模式与 schema 一致。

额外

如果想要在输出中查看此操作的详细日志,可以类似如下配置:

<logger name="org.springframework.jdbc.datasource.init" level="DEBUG"/>

Over

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章