spring jdbc:initialize-database使用详解

本文详细介绍了如何使用Spring的org.springframework.jdbc.datasource.init模块在项目启动时执行数据库初始化操作。通过XML配置,可以轻松指定用于创建数据库表和填充测试数据的SQL脚本。

Org.springframework.jdbc.datasource.init使用详解

org.springframework.jdbc.datasource.init支持在项目启动的时候对数据库的初始化操作。

一、使用方式:使用Spring XML进行初始化数据库(Initializing a database using Spring XML)

a).首先需要为XML加上spring-jdbc命名空间    xmlns:jdbc="http://www.springframework.org/schema/jdbc"

xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd" 

b).在配置文件加入initialize-database标签配置

<jdbc:initialize-database data-source="dataSource" enabled="true"  ignore-failures="NONE" separator="@@">

<jdbc:script location="classpath:com/foo/sql/db-schema.sql"/>

<jdbc:script location="classpath:com/foo/sql/db-test-data.sql"/>

</jdbc:initialize-database>

上面实例的scripts指定了两种不同的脚本,一种是创建数据库表,一种作为测试数据。当然,该脚本支持匹配模式,即多个数据库时候可以使用classpath*:/com/foo/**/sql/*-data.sql进行通配。

二、参数详解

jdbc:initialize-database标签中有一些可配置的参数选项,用配置数据库初始化的一些事件行为。

a).dataSource配置好的数据源。

b).enabled 是用来表明初始化数据库是否执行。这个enabled的值是一个boolean值。设置方法有两种:直接设置truefalse;或者读取配置文件来设置。

示例:

1、直接设置

<jdbc:initialize-database data-source="dataSource" enabled="true"

    <jdbc:script location="classpath:/add-resources.sql"/>

</jdbc:initialize-database>

2、配置文件读取

        <jdbc:initialize-database data-source="dataSource"  enabled="#{systemProperties.INITIALIZE_DATABASE}">

    <jdbc:script location="classpath:/add-resources.sql"/>

</jdbc:initialize-database>

c).ignore-failures有三个值:NONE,DROPS,ALL

设置为NONE时,不忽略任何错误,当sql执行报错时服务启动终止。

设置为DROPS时,忽略删除错误,如当sql中有一个删除表而表不存在,此时这个错误会被忽略。

设置为ALL时,忽略任何错误。

d).separator分隔标识,可配置,该参数可以配置在jdbc:initialize-database中,会对所有script起作用,当然也可以在jdbc:script中单个配置

jdbc:script配置之后,则该script的分隔符使用jdbc:script配置中的。

示例:

<jdbc:initialize-database data-source="dataSource" eparator="@@">

   <jdbc:script location="classpath:com/foo/sql/db-schema.sql" separator=";"/>

<jdbc:script location="classpath:com/foo/sql/db-test-data-1.sql"/>

  <jdbc:script location="classpath:com/foo/sql/db-test-data-2.sql"/>

</jdbc:initialize-database>

此时第一个脚本分隔符为;,剩余两个脚本使用@@

特别的:默认不配置的情况下,sql语句直接必须使用;分开,或者当整个script不存在;时每行一个sql语句。

 

附:spring官方文档链接(part 15.9

http://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/

server: servlet: context-parameters: messageConfig: ZWBMessageConfig, MessageConfig, SCLAMessageConfig error.whitelabel.enabled: false compression.enabled: true tomcat: max-connections: ${TOMCAT_MAX_CONNECTIONS:8192} threads: max: ${TOMCAT_THREADS_MAX:200} min-spare: ${TOMCAT_THREADS_MIN_SPARE:200} port: 8081 shutdown: graceful spring: # 参考 https://docs.spring.io/spring-boot/appendix/application-properties/index.html config: import: # ロジックシナリオ定義YAMLファイル - logic-scenario-default.yml - logic-scenario.yml datasource: driver-class-name: org.postgresql.Driver url: jdbc:postgresql://${POSTGRESQL_HOST:192.168.22.247}:${POSTGRESQL_PORT:5433}/${POSTGRESQL_DATABASE:postgres} username: ${POSTGRESQL_USER:postgres} password: ${POSTGRESQL_PASSWORD:postgres} tomcat: # 参考 https://docs.spring.io/spring-boot/appendix/application-properties/index.html#application-properties.data.spring.datasource.tomcat default-auto-commit: false min-idle: ${DATASOURCE_TOMCAT_MIN_IDLE:2} initial-size: ${DATASOURCE_TOMCAT_INITIALIZE_SIZE:2} max-idle: ${DATASOURCE_TOMCAT_MAX_IDLE:2} max-active: ${DATASOURCE_TOMCAT_MAX_ACTIVE:2} test-while-idle: ${DATASOURCE_TOMCAT_TEST_WHILE_IDLE:true} time-between-eviction-runs-millis: ${DATASOURCE_TOMCAT_TIME_BETWEEN_EVICTION_RUNS_MILLIS:3000000} validation-query: ${DATASOURCE_TOMCAT_VALIDATION_QUERY:SELECT 1} validation-query-timeout: ${DATASOURCE_TOMCAT_VALIDATION_QUERY_TIMEOUT:3} max-wait: ${DATASOURCE_TOMCAT_MAX_WAIT:3000} connection-properties: connectTimeout=${DATASOURCE_TOMCAT_CONNECTTIMEOUT:3};socketTimeout=${DATASOURCE_TOMCAT_SOCKETTIMEOUT:300};ApplicationName=${spring.application.name}; # rpf-zwb-readonly-datasource: # # リードオンリーデータソース設定 # # PostgreSQL JDBC # driver-class-name: org.postgresql.Driver # url: jdbc:postgresql://${POSTGRESQL_RO_HOST:localhost}:${POSTGRESQL_RO_PORT:15432}/${POSTGRESQL_RO_DATABASE:webap_dev} # username: ${POSTGRESQL_RO_USER:webap_dev_user} # password: ${POSTGRESQL_RO_PASSWORD:MyPassword@123} # tomcat: # # 参考 https://docs.spring.io/spring-boot/appendix/application-properties/index.html#application-properties.data.spring.datasource.tomcat # default-auto-commit: false # min-idle: ${DATASOURCE_RO_TOMCAT_MIN_IDLE:2} # initial-size: ${DATASOURCE_RO_TOMCAT_INITIALIZE_SIZE:2} # max-idle: ${DATASOURCE_RO_TOMCAT_MAX_IDLE:2} # max-active: ${DATASOURCE_RO_TOMCAT_MAX_ACTIVE:2} # test-while-idle: ${DATASOURCE_RO_TOMCAT_TEST_WHILE_IDLE:true} # time-between-eviction-runs-millis: ${DATASOURCE_RO_TOMCAT_TIME_BETWEEN_EVICTION_RUNS_MILLIS:3000000} # validation-query: ${DATASOURCE_RO_TOMCAT_VALIDATION_QUERY:SELECT 1} # validation-query-timeout: ${DATASOURCE_RO_TOMCAT_VALIDATION_QUERY_TIMEOUT:3} # max-wait: ${DATASOURCE_RO_TOMCAT_MAX_WAIT:300000} # connection-properties: connectTimeout=${DATASOURCE_RO_TOMCAT_CONNECTTIMEOUT:3};socketTimeout=${DATASOURCE_RO_TOMCAT_SOCKETTIMEOUT:300};ApplicationName=${spring.application.name}; transaction: default-timeout: ${TRANSACTION_DEFAULTTIMEOUT:300} jackson: # JSON項目名のCase規則 property-naming-strategy: SNAKE_CASE # LOWER_CAMEL_CASE / LOWER_CASE / SNAKE_CASE / UPPER_CAMEL_CASE / KEBAB_CASE # JSONパーサー設定 parser: INCLUDE_SOURCE_IN_LOCATION: false # ソース参照情報(JSON内容)を含めない # JSONデシリアライズ設定 deserialization: FAIL_ON_UNKNOWN_PROPERTIES: true # DTOに未定義のフィールドを検知するとエラーとする # JSON日付フォーマット指定 date-format: "yyyy-MM-dd'T'HH:mm:ssXXX" time-zone: "Asia/Tokyo" kafka: bootstrap-servers: ${KAFKA_BROKER_LIST:192.168.22.215}:9092 jaas.enabled: true properties.security.protocol: ${KAFKA_SECURITY_PROTOCOL:PLAINTEXT} properties.sasl.mechanism: ${KAFKA_SASL_MECHANISM:GSSAPI} properties.sasl.jaas.config: org.apache.kafka.common.security.plain.PlainLoginModule required username="${KAFKA_USER:null}" password="${KAFKA_PASSWORD:null}"; consumer: auto-offset-reset: earliest cloud: gcp: firestore: enabled: false function: definition: ssha5007Consumer; stream: # 参考 https://docs.spring.io/spring-cloud-stream/docs/4.1.x/reference/html/spring-cloud-stream.html#_configuration_options default: consumer: maxAttempts: ${KAFKA_BINDINGS_CONSUMER_MAX_ATTEMPTS:3} backOffInitialInterval: ${CONSUMER_RETRY_INTERVAL:1000} bindings: ssha5007Consumer-in-0: destination: ${POS_INFORMATION_OUTPUT_TOPIC:ane-1-shelf-dev-7-topic} group: ssha5007Consumer-in-group contentType: application/json consumer: partitioned: true concurrency: ${KAFKA_BINDINGS_CONSUMER_CONCURRENCY:1} warmup-out-0: destination: ${BINDINGS_DESTINATION_WARMUP_TOPIC:online-warmup-dummy-topic} contentType: application/json kafka: # 参考 https://docs.spring.io/spring-cloud-stream/docs/4.1.x/reference/html/spring-cloud-stream-binder-kafka.html#_configuration_options binder: brokers: ${KAFKA_BROKER_LIST:localhost} autoCreateTopics: true configuration: security: protocol: ${KAFKA_SECURITY_PROTOCOL:PLAINTEXT} sasl: jaas: config: org.apache.kafka.common.security.plain.PlainLoginModule required username="${KAFKA_USER:null}" password="${KAFKA_PASSWORD:null}"; mechanism: ${KAFKA_SASL_MECHANISM:GSSAPI} # Producer Configuration retries: 3 batch.size: 16384 linger.ms: 1 enable.idempotence: true buffer.memory: 33554432 request.timeout.ms: 3000 transaction.timeout.ms: 3000 # Not to use spring.cloud.stream.kafka.binder.required-acks to avoid a bug. # https://github.com/spring-cloud/spring-cloud-stream-binder-kafka/issues/558 acks: "all" # Consumer Configuration isolation.level: read_committed max.poll.records: 1 max.poll.interval.ms: 1020000 auto-add-partitions: true min-partition-count: ${KAFKA_PARTITION_COUNT:1} replicationFactor: -1 transaction: transaction-id-prefix: ${spring.application.name}-${random.uuid} enableObservation: true bindings: ssha5007Consumer-in-0: consumer: enable-dlq: true dlq-name: ${POS_JOURNAL_DEAD_LETTER:ane-1-shelf-dev-7-dead-letter} autoCommitOnError: false application: name: shelf-subscriber-ssha5007-application mybatis: # 参考 https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#configuration mapper-locations: - classpath*:/jp/co/sej/ssc/**/*-sql-map.xml # サンプルAP用SQL Mapファイル configuration: map-underscore-to-camel-case: true default-statement-timeout: ${MYBATIS_DEFAULT_STATEMENTTIMEOUT:300} log-impl: ${MYBATIS_LOG_IMPL:org.apache.ibatis.logging.stdout.StdOutImpl} # ログ設定 logging: level: # root: info # web: trace # sql: debug # org.springframework: # security: info com.nec.jp.rpf.zwb.framework: info com.nec.jp.rpf.zcp.framework: info '[jp.co.sej.ssc]': ${AP_LOG_LEVEL:INFO} '[jp.co.sej.ssc.cl]': ${AP_LOG_LEVEL_CL:WARN} # フレームワーク設定 rpf-zwb-framework: # アプリケーションサービスタイプ指定。 サービスのタイプによってrest/subscriberのいずれかを指定。省略時はrest。 application-service-type: subscriber # データソースルーティング設定 single / primary-and-readonly # プライマリーおよび、リードオンリーデータソース利用時は primary-and-readonly を指定。 # 単一データソース利用時は single を指定。 # 項目省略時は single # datasource-routing: primary-and-readonly # フレームワークロガー設定 logger: operation: # リクエスト・レスポンス JSONマスキングログ出力設定 masking-logger: masked-output-value: xxmaskedxx # マスキング出力文字列を指定。 項目省略時は '**masked**' rest-api: # REST APIサービス request-logging: true # リクエストログ出力 出力する:true / 出力しない:false 項目省略時は false response-logging: true # レスポンスログ出力 出力する:true / 出力しない:false 項目省略時は false rest-cooperation: # RESTサービス連携 request-logging: true # リクエストログ出力 出力する:true / 出力しない:false 項目省略時は false response-logging: true # レスポンスログ出力 出力する:true / 出力しない:false 項目省略時は false stream-subscriber: # 分散メッセージング(Pub/Sub) Subscriber サービス subscribe-logging: true # サブスクライブログ出力 出力する:true / 出力しない:false 項目省略時は false stream-publisher: # 分散メッセージング(Pub/Sub) Publisher publish-logging: true # パブリッシュログ出力 出力する:true / 出力しない:false 項目省略時は false cloud: stream: # Subscriber サービス設定 subscriber: # 業務ロジックのResultTypeに対する例外スロー対象を設定。FATAL/ERROR/WARN を指定。その他の値や指定がない場合は例外スローしません。 # DLQを設定している場合、例外スローにより該当メッセージがDLQに格納されます。 # throw-exception-level: FATAL # SubscriberでシナリオロジックサービスのシナリオID引数を省略した場合のシナリオID default-scenario-id: SUBSCRIBE_SSHA5007 # サンプルAP設定(テスト用) rpf-zwb-example: test-property: testvalue # Spring Boot Actuator設定 management: health: pubsub: enabled: false # 参考 https://docs.spring.io/spring-boot/appendix/application-properties/index.html#appendix.application-properties.actuator endpoints: web: base-path: / health: probes.enabled: true # Kubernetes Probes # Micrometer Tracing用 tracing: baggage: # HTTPヘッダーで渡される情報とBaggageで渡されるキーを定義 remote-fields: requester, X-DELIVERY-STORE-DIVISION, baggageInfo correlation: # requesterは指定せず、ロジックでThreadContextに取り込む。指定すると、Baggage操作、Baggage送信時に更新されるため fields: baggageInfo propagation: type: B3 sampling: probability: 0.0 # RESTサービス連携 cooperation: time-options: read-timeout: ${COOPERATION_TIMEOPTIONS_READTIMEOUT:5000} connect-timeout: ${COOPERATION_TIMEOPTIONS_CONNECTTIMEOUT:3000} retry-limit: ${COOPERATION_TIMEOPTIONS_RETRYLIMIT:0} domain-name: ${COOPERATION_DOMAIN_NAME:localdomain} retry-for-kafka: # retryable-exceptions-disabled: true retryable-exceptions: org.apache.kafka.common.errors.UnknownProducerIdException: true org.apache.kafka.common.errors.InvalidPidMappingException: true traverse-causes: true 哪个是管运行超时的
10-10
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值