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

  1. 项目结构

  1. schema.sql
  1. drop table if exists user;
  2. create table user (id bigint(20) not null auto_increment,
  3. username varchar(40) DEFAULT NULL,
  4. name varchar(20) DEFAULT NULL,
  5. age int(3) DEFAULT NULL,
  6. balance decimal(10,2) DEFAULT NULL,
  7. primary key(id))ENGINE=InnoDB DEFAULT CHARSET=utf8; 
  1. data.sql
  1. insert into user (id, username, name, age, balance) values (1,'account1','张三', 20, 100.00);
  2. insert into user (id, username, name, age, balance) values (2,'account2','李四', 28, 180.00);
  3. insert into user (id, username, name, age, balance) values (3,'account3','王五', 32, 280.00);
  1. SpringBoot1.x中, 运行schema.sql不需要配置便可之间运行,但是在SpringBoot2.x中,我们需要在配置文件中配置一下:
  1. spring.datasource.initialization-mode: always
  1. 数据库配置:
  1. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  2. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test-xc?useSSL=false&useUnicode=true&characterEncoding=UTF8
  3. spring.datasource.username=root
  4. spring.datasource.password=root
  5. spring.datasource.platform=mysql
  6. spring.datasource.separator=;
  7. spring.datasource.schema=classpath:schema.sql
  8. spring.datasource.data=classpath:data.sql
  9. spring.datasource.initialization-mode=always
  10.  
  11. #显示SQL语句
  12. spring.jpa.show-sql=true
  13. #不加下面这句则不会默认创建MyISAM引擎的数据库
  14. spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
  1. spring.datasource下有两个属性  schmedata,其中schema为表初始化语句,data为数据初始化,默认加载schema.sqldata.sql。脚本位置可以通过spring.datasource.schema  spring.datasource.data 来改变,源码如下:
  1. /**
  2. * Create the schema if necessary.
  3. * @return {@code true} if the schema was created
  4. * @see DataSourceProperties#getSchema()
  5. */
  6. public boolean createSchema() {
  7. List<Resource> scripts = getScripts("spring.datasource.schema",
  8. this.properties.getSchema(), "schema");
  9. if (!scripts.isEmpty()) {
  10. if (!isEnabled()) {
  11. logger.debug("Initialization disabled (not running DDL scripts)");
  12. return false;
  13. }
  14. String username = this.properties.getSchemaUsername();
  15. String password = this.properties.getSchemaPassword();
  16. runScripts(scripts, username, password);
  17. }
  18. return !scripts.isEmpty();
  19. }
  20.  
  21. /**
  22. * Initialize the schema if necessary.
  23. * @see DataSourceProperties#getData()
  24. */
  25. public void initSchema() {
  26. List<Resource> scripts = getScripts("spring.datasource.data",
  27. this.properties.getData(), "data");
  28. if (!scripts.isEmpty()) {
  29. if (!isEnabled()) {
  30. logger.debug("Initialization disabled (not running data scripts)");
  31. return;
  32. }
  33. String username = this.properties.getDataUsername();
  34. String password = this.properties.getDataPassword();
  35. runScripts(scripts, username, password);
  36. }
  37. }

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

  1. private List<Resource> getScripts(String propertyName, List<String> resources,
  2. String fallback) {
  3. if (resources != null) {
  4. return getResources(propertyName, resources, true);
  5. }
  6. String platform = this.properties.getPlatform();
  7. List<String> fallbackResources = new ArrayList<>();
  8. fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
  9. fallbackResources.add("classpath*:" + fallback + ".sql");
  10. return getResources(propertyName, fallbackResources, false);
  11. }

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

  1. /*
  2. * Copyright 2012-2017 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16.  
  17. package org.springframework.boot.jdbc;
  18.  
  19. /**
  20. * Supported {@link javax.sql.DataSource} initialization modes.
  21. *
  22. * @author Vedran Pavic
  23. * @author Stephane Nicoll
  24. * @since 2.0.0
  25. * @see AbstractDataSourceInitializer
  26. */
  27. public enum DataSourceInitializationMode {
  28.  
  29. /**
  30. * Always initialize the datasource.
  31. */
  32. ALWAYS,
  33.  
  34. /**
  35. * Only initialize an embedded datasource.
  36. */
  37. EMBEDDED,
  38.  
  39. /**
  40. * Do not initialize the datasource.
  41. */
  42. NEVER
  43.  
  44. }

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初始化数据库

  1. spring:
  2. jpa:
  3. show-sql: true
  4. #启动时是否初始化数据库-hibernate
  5. generate-ddl: false
  6. hibernate:
  7. 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

  1.  

Springboot2.x 自动创建表并且执行初始化数据的更多相关文章

  1. Hibernate连接mysql数据库并自动创建表

    天才第一步,雀氏纸尿裤,Hibernate第一步,连接数据库. Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个 ...

  2. Hibernate自动创建表

    只要在hibernate.cfg.xml添加这句话,就可以自动生成数据表 <property name="hibernate.hbm2ddl.auto">update& ...

  3. mysql 按照月份自动创建表,以年和月为表明,动态生成。

    需求:mysql5.5 数据库,想要根据月份自动创建表,每个月创建一张表,需要数据库自动创建,并根据当前年和月动态生成表名称. 解决办法:1 连接数据库工具为Navicat  2  首先创建存储过程, ...

  4. Hibernate 自动创建表bug问题解决

    我在hibernate.cfg.xml配置文件中添加了自动创建表的的属性:(这样当数据库中没有此表是,hibernate就会自动帮我们创建一张表) <property name="hb ...

  5. 在mysql数据库中创建oracle scott用户的四个表及插入初始化数据

    在mysql数据库中创建oracle scott用户的四个表及插入初始化数据 /* 功能:创建 scott 数据库中的 dept 表 */ create table dept( deptno int ...

  6. Hibernate根据实体类自动创建表

    Hibernate支持自动建表,在开发阶段很方便,可以保证hbm与数据库表结构的自动同步. 如何使用呢?很简单,只要在hibernate.cfg.xml里加上如下代码 Xml代码<propert ...

  7. hibernate自动创建表报表不存在

    在hibernate.cfg.xml配置了<property name="hibernate.hbm2ddl.auto">update</property> ...

  8. sql自动创建表并复制数据

    ---------------自动创建表并复制数据sql,需要自己设置主键----------- select * into 新表 from 旧表

  9. SQL Server ->> 自动创建表并从文件加载数据

    这个存储过程自动创建表并从文件加载数据. 有一点需要说明的是Excel 12.0驱动是兼容了Excel 97-2003和Excel 2007两者格式的Excel文件. CREATE PROCEDURE ...

随机推荐

  1. 放出一批jsp图书管理系统图书借阅系统源码代码运行

    基于jsp+mysql的JSP图书销售管理系统 https://www.icodedock.com/article/105.html基于jsp+Spring+Spring MVC的Spring图书借阅 ...

  2. WPF:事件委托对于不同界面间通信的应用

    界面1内设定点击事件,生成Path用事件传出public partial class TemplateWindow : Window     {         internal delegate v ...

  3. 【React踩坑记四】React项目中引入并使用js-xlsx上传插件(结合antdesign的上传组件)

    最近有一个前端上传并解析excel/csv表格数据的需求. 于是在github上找到一个14K star的前端解析插件 github传送门 官方也有,奈何实在太过于浅薄.于是做了以下整理,避免道友们少 ...

  4. Windows to Linux API 映射

  5. Java中的魔法类-Unsafe

    Unsafe是位于sun.misc包下的一个类,主要提供一些用于执行低级别.不安全操作的方法,如直接访问系统内存资源.自主管理内存资源等,这些方法在提升Java运行效率.增强Java语言底层资源操作能 ...

  6. HTML/CSS:block,inline和inline-block概念和区别

    总体概念 block和inline这两个概念是简略的说法,完整确切的说应该是 block-level elements (块级元素) 和 inline elements (内联元素).block元素通 ...

  7. dart的基本语法(一)

    Hello world ​ 安装dart的环境就不赘述了,无脑安装就可以了,安装过程中好像需要梯子(vpn),我装的时候失败好多次,我的梯子不能用了,准备不装了的时候,莫名其妙的装好了.迷の操作.惯例 ...

  8. 关于Oracle本地连接出现与监听有关的问题的解决方法探讨

    关于Oracle本地连接出现与监听有关的问题的解决方法探讨 监听的作用: 用于应用桌面即用户与数据库服务器建立连接的媒介,客户端发送连接请求,监听识别请求并建立客户端与服务器的连接后,监听的使命并完成 ...

  9. Zabbix-绘制动态拓扑图高级篇

    0.官网文档介绍: https://www.zabbix.com/documentation/4.0/manual/config/visualisation/maps/map 一.设备名字使用宏显示 ...

  10. cocos creator 事件

    cocos creator 事件 在做一个消除类游戏时,需要对点击的方块做出响应.代码很简单,可背后的原理还多着呢. 1. 普通节点注册click事件 在cc中如果需要相应click事件,需要为该节点 ...