如何在应用程序启动时运行SQL脚本并获取数据? [英] How to run SQL scripts and get data on application startup?
问题描述
我正在开发一个Spring Boot应用程序.目前,我的一些配置已经过硬编码(例如Hystrix属性).
I am developing a Spring Boot application. At the moment some of my configs are hard coded (e.g. Hystrix properties).
所以我想在我的应用程序启动时间或之后启动这些配置.
So I would like to get these configs on my application start up time or just after that.
是否可以使用Spring Boot做到这一点?我的意思是在启动时运行SQL脚本并获取数据.
Is it possible to do that using Spring Boot? I mean to run SQL script on start up and get data.
应如何检索属性/配置并将其存储在我的应用程序中?
How should properties/configs be retrieved and stored in my application?
我正在使用MyBatis和Oracle DB.
I am using MyBatis and Oracle DB.
推荐答案
默认情况下,Spring-Boot加载data.sql
和/或data-${platform}.sql
.
By default, Spring-Boot loads data.sql
and/or data-${platform}.sql
.
但是,请记住,该脚本将在每次启动时加载,因此,我认为(至少对于生产而言)有意义的是,只保留数据库中已经存在的值,而不是每次都重新插入开始. 我个人仅在使用内存数据库时将数据库初始化用于测试/开发目的.不过,这是Spring-Boot提供的功能.
However, keep in mind that the script would be loaded at every start, so I would think it makes more sense (at least for production), to just have the values already present in the database, not re-inserted at every start. I've personally only used database initialization for test/dev purposes when using a memory database. Still, this is the feature provided by Spring-Boot.
来源: spring-boot- howto-数据库初始化:
Spring JDBC具有数据源初始化器功能. Spring Boot启用 默认情况下,它会从标准位置schema.sql和 data.sql(在类路径的根目录中).此外,Spring Boot将 加载架构$$ {platform} .sql和数据$$ {platform} .sql文件(如果 礼物).
Spring JDBC has a DataSource initializer feature. Spring Boot enables it by default and loads SQL from the standard locations schema.sql and data.sql (in the root of the classpath). In addition Spring Boot will load the schema-${platform}.sql and data-${platform}.sql files (if present).
src/main/resources/ data-oracle.sql:
src/main/resources/data-oracle.sql:
insert into...
insert into...
- 您可以使用以下代码定义平台:
spring.datasource.platform=oracle
. - 您可以更改要加载的sql脚本的名称:
spring.datasource.data=myscript.sql
. - 与
data.sql
一样,Spring-boot也会加载schema.sql
(在data.sql
之前). - 您还可以在data.sql中添加更新或插入"逻辑:
- You may define the platform with:
spring.datasource.platform=oracle
. - You may change the name of the sql script to load with:
spring.datasource.data=myscript.sql
. - Along with
data.sql
, Spring-boot also loadsschema.sql
(beforedata.sql
). - You could also have an "update or insert" logic in your data.sql: oracle sql: update if exists else insert
这篇关于如何在应用程序启动时运行SQL脚本并获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- You may define the platform with: