首页 > 数据库 >Spring Boot启动时数据库初始化spring.datasource(转)

Spring Boot启动时数据库初始化spring.datasource(转)

时间:2022-11-02 15:01:49浏览次数:61  
标签:String spring Spring Boot datasource sql data schema

原文:https://blog.csdn.net/u012326462/article/details/82080812

1.使用springboot jdbc初始化数据库

spring:
  datasource:
    username: xuhaixing
    password: xuhaixing
    url: jdbc:mysql://192.168.94.151:3306/mytest?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
    driver-class-name: com.mysql.jdbc.Driver
    platform: mysql
    #启动时需要初始化的建表语句
    schema: classpath:schema-mysql.sql
    #初始化的数据
    data: classpath:data-mysql.sql
    # Initialize the datasource with available DDL and DML scripts.
    initialization-mode: always
    continue-on-error: false
    #data-password:
    #data-username:
    #schema-password:
    #schema-username:
    sql-script-encoding: utf-8
    separator: ;

spring.datasource下有两个属性 schme、data,其中schema为表初始化语句,data为数据初始化,默认加载schema.sql与data.sql。脚本位置可以通过spring.datasource.schema 与spring.datasource.data 来改变,源码如下:

/**
     * Create the schema if necessary.
     * @return {@code true} if the schema was created
     * @see DataSourceProperties#getSchema()
     */
    public boolean createSchema() {
        List<Resource> scripts = getScripts("spring.datasource.schema",
                this.properties.getSchema(), "schema");
        if (!scripts.isEmpty()) {
            if (!isEnabled()) {
                logger.debug("Initialization disabled (not running DDL scripts)");
                return false;
            }
            String username = this.properties.getSchemaUsername();
            String password = this.properties.getSchemaPassword();
            runScripts(scripts, username, password);
        }
        return !scripts.isEmpty();
    }
 
    /**
     * Initialize the schema if necessary.
     * @see DataSourceProperties#getData()
     */
    public void initSchema() {
        List<Resource> scripts = getScripts("spring.datasource.data",
                this.properties.getData(), "data");
        if (!scripts.isEmpty()) {
            if (!isEnabled()) {
                logger.debug("Initialization disabled (not running data scripts)");
                return;
            }
            String username = this.properties.getDataUsername();
            String password = this.properties.getDataPassword();
            runScripts(scripts, username, password);
        }
    }

看getScripts源码,它还会加载schema-${platform}.sql文件,或者data-${platform}.sql文件,其中platform就是spring.datasource.platform的值

 
    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<>();
        fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
        fallbackResources.add("classpath*:" + fallback + ".sql");
        return getResources(propertyName, fallbackResources, false);
    }
    
    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<>();
        fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
        fallbackResources.add("classpath*:" + fallback + ".sql");
        return getResources(propertyName, fallbackResources, false);
    }

spring.datasource.initialization-mode  初始化模式(springboot2.0),其中有三个值,always为始终执行初始化,embedded只初始化内存数据库(默认值),如h2等,never为不执行初始化。

/*
 * Copyright 2012-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package org.springframework.boot.jdbc;
 
/**
 * Supported {@link javax.sql.DataSource} initialization modes.
 *
 * @author Vedran Pavic
 * @author Stephane Nicoll
 * @since 2.0.0
 * @see AbstractDataSourceInitializer
 */
public enum DataSourceInitializationMode {
 
    /**
     * Always initialize the datasource.
     */
    ALWAYS,
 
    /**
     * Only initialize an embedded datasource.
     */
    EMBEDDED,
 
    /**
     * Do not initialize the datasource.
     */
    NEVER
 
}

spring.datasouce.data-password:

spring.datasouce.data-username:

spring.datasouce.schema-password:

spring.datasouce.schema-username:

这四个值为执行schema.sql或者data.sql时,用的用户

 

spring.datasource.sql-script-encoding: utf-8 为文件的编码

spring.datasource.separator: ; 为sql脚本中语句分隔符

spring.datasource.continue-on-error: false 遇到语句错误时是否继续,若已经执行过某些语句,再执行可能会报错,可以忽略,不会影响程序启动

标签:String,spring,Spring,Boot,datasource,sql,data,schema
From: https://www.cnblogs.com/ajianbeyourself/p/16851019.html

相关文章

  • 爱上源码,重学Spring MVC深入
    1.1gradle搭建源码调试环境1)搭建gradle环境4个步骤1、File-New-Module选择java和web2、填写包信息3、存储路径2)增加起步依赖依赖的项目,直接复制粘贴上去1、对......
  • SpringBoot笔记:控制类Controller
    一个类想要变成控制类,只需要在类上加一个@Controller注解即可,其作用为指定请求路径及其对应的处理方法。一、请求路径常用注解:可以直接使用@RequestMapping、@PostMappi......
  • SpringBoot+Vue+token实现(表单+图片)上传、图片地址保存到数据库。上传图片保存位置自
    1、大致思路以下是基于先处理图片、后端返回图片地址进行的==存数据==1、将图片信息提交到后端2、后端处理3、后端返回前端图片的访问地址4、前端将图片地址存入要提......
  • 653 Bootstrap_全局cSS样式_按钮&图片 amd 654 Bootstrap_全局cSS样式2_表格&表单
    CSS样式和JS插件Bootstrap_全局cSS样式_按钮&图片全局样式按钮:class="btnbtn-default"图片:1.class="img-responsive":图片在任意尺寸都占100%......
  • SpringBoot项目启动后直接退出
    一、问题背景​ 利用idea新建一个springbootModel,默认只选择了一个依赖二、报错截图如下三、我的项目配置如下​ 没有添加springboot工程的依赖四、分析问题​ 发......
  • 关于SpringMvc使用@RequstBody报错500的原因
    在使用SpringMvc框架接收前端数据添加到数据库时报500错误,@PostMappingpublicResultsave(@RequestBodyBookbook){booleanflag=bookService.save......
  • Spring中注解---事务注解 @Transactional中的属性与值
    @Transactional修饰范围:类上或方法上作用:给类中方法加入事务,当类上和方法上同时存在该注解时方法优先注解属性:propagation:控制事务传播属性......
  • [JAVA]Springboot添加fastjson用于前台数据校验
    方式一,添加HttpMessageConverters实例importcom.alibaba.fastjson.support.config.FastJsonConfig;importcom.alibaba.fastjson.support.spring.FastJsonHttpMessage......
  • SpringMVC
    SpringMVC简述是基于spring的一个框架,实际上就是spring的一个模块,专门做web开发的。可理解为servlet的一个升级。web开发底层是servlet,框架是在servlet基础......
  • Spring Session
    Session会话管理概述Web中的Session和Cookie回顾Session机制由于HTTP协议是无状态的协议,一次浏览器和服务器的交互过程就是:浏览器:你好吗?服务器:很好!这就是一次......