日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring 执行 sql 脚本(文件)

發布時間:2025/3/21 javascript 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 脚本(文件)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。