當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring 执行 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";@Autowiredprivate DataSource datasource;@Autowiredprivate 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;}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}}備注:
關于為何 Spring 會去執行 classpath:schema.sql,可以參考源碼
org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer#runSchemaScripts
private void runSchemaScripts() {List<Resource> 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<Resource> getScripts(String propertyName, List<String> resources,String fallback) {if (resources != null) {return getResources(propertyName, resources, true);}String platform = this.properties.getPlatform();List<String> fallbackResources = new ArrayList<String>();fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");fallbackResources.add("classpath*:" + fallback + ".sql");return getResources(propertyName, fallbackResources, false);}參考:https://github.com/spring-pro...
原文鏈接:
http://zhige.me/2019/02/28/20...
總結
以上是生活随笔為你收集整理的Spring 执行 sql 脚本(文件)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux删除文件后,空间未释放的一种情
- 下一篇: 4.50Nginx负载均衡