java 执行sql脚本文件_Spring执行sql脚本文件的方法

本篇解决 Spring 执行SQL脚本(文件)的问题。

场景描述可以不看。

场景描述:

我在运行单测的时候,也就是 Spring 工程启动的时候,Spring 会去执行 classpath:schema.sql(后面会解释),我想利用这一点,解决一个问题:

一次运行多个测试文件,每个文件先后独立运行,而上一个文件创建的数据,会对下一个文件运行时造成影响,所以我要在每个文件执行完成之后,重置数据库,不单单是把数据删掉,而 schema.sql 里面有 drop table 和create table。

解决方法:

//Schema 处理器

@Component

public class SchemaHandler {

private final String SCHEMA_SQL = "classpath:schema.sql";

@Autowired

private DataSource datasource;

@Autowired

private SpringContextGetter springContextGetter;

public void execute() throws Exception {

Resource resource = springContextGetter.getApplicationContext().getResource(SCHEMA_SQL);

ScriptUtils.executeSqlScript(datasource.getConnection(), resource);

}

}

// 获取 ApplicationContext

@Component

public class SpringContextGetter implements ApplicationContextAware {

private ApplicationContext applicationContext;

public ApplicationContext getApplicationContext() {

return applicationContext;

}

@Override

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

this.applicationContext = applicationContext;

}

}

备注:

关于为何 Spring 会去执行 classpath:schema.sql,可以参考源码

org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer#runSchemaScripts

private void runSchemaScripts() {

List scripts = getScripts("spring.datasource.schema",

this.properties.getSchema(), "schema");

if (!scripts.isEmpty()) {

String username = this.properties.getSchemaUsername();

String password = this.properties.getSchemaPassword();

runScripts(scripts, username, password);

try {

this.applicationContext

.publishEvent(new DataSourceInitializedEvent(this.dataSource));

// The listener might not be registered yet, so don't rely on it.

if (!this.initialized) {

runDataScripts();

this.initialized = true;

}

}

catch (IllegalStateException ex) {

logger.warn("Could not send event to complete DataSource initialization ("

+ ex.getMessage() + ")");

}

}

}

/**

* 默认拿 classpath*:schema-all.sql 和 classpath*:schema.sql

*/

private List getScripts(String propertyName, List resources,

String fallback) {

if (resources != null) {

return getResources(propertyName, resources, true);

}

String platform = this.properties.getPlatform();

List fallbackResources = new ArrayList();

fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");

fallbackResources.add("classpath*:" + fallback + ".sql");

return getResources(propertyName, fallbackResources, false);

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值