Springboot2.x 自动创建表并且执行初始化数据
1.使用springboot jdbc初始化数据库
项目结构

schema.sql
drop table if exists user;
create table user (id bigint(20) not null auto_increment,
username varchar(40) DEFAULT NULL,
name varchar(20) DEFAULT NULL,
age int(3) DEFAULT NULL,
balance decimal(10,2) DEFAULT NULL,
primary key(id))ENGINE=InnoDB DEFAULT CHARSET=utf8;
data.sql
insert into user (id, username, name, age, balance) values (1,'account1','张三', 20, 100.00);
insert into user (id, username, name, age, balance) values (2,'account2','李四', 28, 180.00);
insert into user (id, username, name, age, balance) values (3,'account3','王五', 32, 280.00);
在SpringBoot1.x中, 运行schema.sql不需要配置便可之间运行,但是在SpringBoot2.x中,我们需要在配置文件中配置一下:
spring.datasource.initialization-mode: always
数据库配置:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test-xc?useSSL=false&useUnicode=true&characterEncoding=UTF8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.platform=mysql
spring.datasource.separator=;
spring.datasource.schema=classpath:schema.sql
spring.datasource.data=classpath:data.sql
spring.datasource.initialization-mode=always #显示SQL语句
spring.jpa.show-sql=true
#不加下面这句则不会默认创建MyISAM引擎的数据库
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
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);
}
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的
转载至Springboot(二十)启动时数据库初始化spring.datasource/spring.jpa
Springboot2.x 自动创建表并且执行初始化数据的更多相关文章
- Hibernate连接mysql数据库并自动创建表
天才第一步,雀氏纸尿裤,Hibernate第一步,连接数据库. Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个 ...
- Hibernate自动创建表
只要在hibernate.cfg.xml添加这句话,就可以自动生成数据表 <property name="hibernate.hbm2ddl.auto">update& ...
- mysql 按照月份自动创建表,以年和月为表明,动态生成。
需求:mysql5.5 数据库,想要根据月份自动创建表,每个月创建一张表,需要数据库自动创建,并根据当前年和月动态生成表名称. 解决办法:1 连接数据库工具为Navicat 2 首先创建存储过程, ...
- Hibernate 自动创建表bug问题解决
我在hibernate.cfg.xml配置文件中添加了自动创建表的的属性:(这样当数据库中没有此表是,hibernate就会自动帮我们创建一张表) <property name="hb ...
- 在mysql数据库中创建oracle scott用户的四个表及插入初始化数据
在mysql数据库中创建oracle scott用户的四个表及插入初始化数据 /* 功能:创建 scott 数据库中的 dept 表 */ create table dept( deptno int ...
- Hibernate根据实体类自动创建表
Hibernate支持自动建表,在开发阶段很方便,可以保证hbm与数据库表结构的自动同步. 如何使用呢?很简单,只要在hibernate.cfg.xml里加上如下代码 Xml代码<propert ...
- hibernate自动创建表报表不存在
在hibernate.cfg.xml配置了<property name="hibernate.hbm2ddl.auto">update</property> ...
- sql自动创建表并复制数据
---------------自动创建表并复制数据sql,需要自己设置主键----------- select * into 新表 from 旧表
- SQL Server ->> 自动创建表并从文件加载数据
这个存储过程自动创建表并从文件加载数据. 有一点需要说明的是Excel 12.0驱动是兼容了Excel 97-2003和Excel 2007两者格式的Excel文件. CREATE PROCEDURE ...
随机推荐
- 如何在docker下安装elasticsearch(上)
一 环境 VMware® Workstation 15 Pro centos7 (1810) docker19.03.1 二 进入centos7启动dcoker systemctl start doc ...
- redis过期策略与内存淘汰机制分析
过期策略: 我们在set key时,可以给一个expire time,就是过期时间 这段过期时间以后,redis对key删除使用:定期删除+惰性删除 定期删除指redis默认在100ms内随机抽取一些 ...
- 自定义ItemToggleView
极力推荐文章:欢迎收藏 Android 干货分享 阅读五分钟,每日十点,和您一起终身学习,这里是程序员Android 本篇文章主要介绍 Android 开发中的部分知识点,通过阅读本篇文章,您将收获以 ...
- swift 分享share页面封装(功能按钮不同)
关于分享功能的页面应该有很多,写这篇swift版本的分享页面,根据不同模块可能分享的功能按钮不一样,引言: 想必大家都使用微博右上角更多按钮,会弹出如下的界面: 在开发中,可能针对同一个app的不同按 ...
- 原生js实现图片懒加载+加入节流
这两天在学习图片的懒加载实现,看了很多大佬的博客,终于有了点成果.现在用了其中一位大佬的文章中的代码实现了图片懒加载并且在其基础上加入了节流函数. 原理就不多讲了,有需要的可以去大佬的文章看看.大佬文 ...
- 【Java例题】6.2 日期类的使用
2.日期类的使用.显示今天的年月日.时分秒和毫秒数.显示今天是星期几.是今年内的第几天.显示本月共几天,今年是不是闰年.显示两个日期的差,包括年月日.时分秒和毫秒差值. package chapter ...
- 100天搞定机器学习|Day 30-32 微积分的本质
3blue1brown系列课程,精美的动画,配上生动的讲解,非常适合帮助建立数学的形象思维,非常值得反复观看: http://www.3blue1brown.com/ 哔哩哔哩: https://sp ...
- win10 将硬盘工作模式由IDE调整到AHCI模式
第1步:重启进入安全模式 1)点击“开始”按钮 进入设置 2)进入“更新和安全”,“恢复-高级启动”,点击“立即高级启动”, 依次选择“疑难解答”-“高级选项”-“启动设置”-点击“重启” 第2步:进 ...
- GOF23-单列模式
1.什么是单例模式 一个类只有一个实列,并且提供一个对外访问该实例的全局访问点. 常见应用场景:数据库连接池,项目中读取配置文件的类,servlet也是单列,Spring中的Bean默认也是单列 2. ...
- Mac 打造开发工作环境
近日公司配的dell笔记本越来越难担重任(主要是CPU太差,本人是Java开发,IDE一编译CPU就100%),于是狠下心入手了一台常规顶配Macbook Pro,现记录新本本的调教过程. Homeb ...