国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Spring Boot中自動執行sql腳本的實現

瀏覽:68日期:2023-04-02 15:31:10

說明:所有的代碼基于SpringBoot 2.0.3版本

背景

在應用程序啟動后,可以自動執行建庫、建表等SQL腳本.下文中以要自動化執行people.sql腳本為例說明,腳本在SpringBoot工程中的路徑為:classpath:people.sql,腳本的具體內容如下:

CREATE TABLE IF NOT EXISTS people( persion_id BIGINT NOT NULL AUTO_INCREMENT, first_name VARCHAR(20), last_name VARCHAR(20), PRIMARY KEY (persion_id));實現核心

在SpringBoot的架構中,DataSourceInitializer類可以實現自動執行腳本的功能。通過自定義DataSourceInitializer Bean就可以實現按照業務要求執行特定的腳本。

實現方法前提

已經構建了DataSource Bean。

方法

通過@Configuration、@Bean和@Value三個注解實現自定義DataSourceInitializer Bean,現在Bean的定義中實現自動化執行腳本的業務邏輯。

代碼

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;@Configurationpublic class BatchTaskDataSourceInitializer { /** * 構建Resource對象 */ @Value('classpath:schema-all.sql') private Resource businessScript; /** * 自定義Bean實現業務的特殊需求 * @param dataSource * @return */ @Bean public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) { final DataSourceInitializer initializer = new DataSourceInitializer(); // 設置數據源 initializer.setDataSource(dataSource); initializer.setDatabasePopulator(databasePopulator()); return initializer; } private DatabasePopulator databasePopulator() { final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScripts(businessScript); return populator; }}

到此這篇關于Spring Boot中自動執行sql腳本的實現的文章就介紹到這了,更多相關SpringBoot自動執行sql內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 宜良县| 南平市| 靖江市| 额敏县| 靖安县| 南溪县| 海兴县| 柳州市| 苍南县| 凤城市| 库尔勒市| 寿光市| 将乐县| 礼泉县| 北海市| 梅河口市| 烟台市| 沁源县| 威远县| 谢通门县| 辰溪县| 镇赉县| 山东| 平陆县| 平和县| 乐亭县| 吉水县| 万荣县| 鞍山市| 杭州市| 陕西省| 荆门市| 新巴尔虎左旗| 南部县| 突泉县| 如皋市| 腾冲县| 竹北市| 家居| 宁南县| 陇西县|