Springboot(二十)启动时数据库初始化spring.datasource/spring.jpa

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.sqldata.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-passwork:

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   遇到语句错误时是否继续,若已经执行过某些语句,再执行可能会报错,可以忽略,不会影响程序启动

 

2.使用hibernate初始化数据库

spring:
  jpa:
    show-sql: true
    #启动时是否初始化数据库-hibernate
    generate-ddl: false
    hibernate:
      ddl-auto: update

generate-ddl: true时,执行schema创建,会检测classpath下的import.sql文件,当然spring.jpa.hibernate.ddl-auto: 必须为create/update/create-drop,none和validate是不行的,因为这个创建时hibernate的,所以建议用spring的

 

 

更多内容请关注微信公众号:程序员星星,博客与csdn同时更新

  • 5
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,您可以按照以下步骤完成SpringBoot工程的初始化,并且连接MsSQL数据库: 1. 在您的IDE中新建一个SpringBoot工程项目。 2. 打开项目中的pom.xml文件,添加下列依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <version>9.2.1.jre15</version> </dependency> </dependencies> ``` 3. 在application.properties文件中添加以下配置: ```properties spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=YourDatabaseName spring.datasource.username=YourUserName spring.datasource.password=YourPassword spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver spring.jpa.hibernate.ddl-auto=update ``` 其中,url中的localhost为您的数据库所在主机地址,1433为数据库端口号,YourDatabaseName为您数据库的名称,YourUserName和YourPassword分别为您的数据库用户名和密码。 4. 在您的主类上添加@EnableJdbcRepositories注解,启动JDBC Repository支持。 ```java @SpringBootApplication @EnableJdbcRepositories public class DemoApplication { //... } ``` 至此,您已经完成了SpringBoot工程初始化并连接上了MsSQL数据库,可以开始您的业务开发了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值