0
点赞
收藏
分享

微信扫一扫

springboot启动时候自动创建数据库表解决方案


首先创建一个springboot的项目

项目结构

springboot启动时候自动创建数据库表解决方案_sql

  1. 导入相关依赖
    mybatis druid mysql驱动三个

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>

  1. springboot 2.3.4.Release版本配置文件配置

spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#项目启动执行建表语句,classpath指定sql文件的位置
schema:
- classpath:sql/init.sql
initialization-mode: always
platform: mysql
sql-script-encoding: UTF-8

springboot 2.6.4版本配置文件配置(谢谢nreg的指出)

spring: 
sql:
init:
separator: ; #断句分隔符,默认为 ; 号,如果执行语句中有 存储过程 或 游标 这种 则需要更改
encoding: UTF-8
platform: sqlite #默认值为all 在不同数据库切换的情况下才使用 all 配置,spring boot 会自动检测当前使用的数据库
mode: always # 初始化模式,有三个值:always:始终执行初始化、embedded:只初始化内存数据库(默认)、never:不执行初始化
schema-locations: #表初始化语句 DDL,默认加载 schema.sql
- classpath:sql/schema.sql
data-locations: #数据初始化 DQL(数据查询)或 DML(数据操作),默认加载 data.sql
- classpath:sql/data.sql

  1. sql文件填写

-- ----------------------------
-- Table structure for t1
-- ----------------------------
DROP TABLE IF EXISTS `t1`;
CREATE TABLE `t1` (
`id` int(11) NOT NULL,
`name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t1
-- ----------------------------
INSERT INTO `t1` VALUES (1, '1');
INSERT INTO `t1` VALUES (2, '2');
INSERT INTO `t1` VALUES (3, '3');

SET FOREIGN_KEY_CHECKS = 1;


举报

相关推荐

0 条评论