SpringBoot2.x自动创建表并初始化数据库

2023-02-25 16:18:21 浏览数 (1)

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

项目结构:

1.1 application.yml配置文件:

代码语言:javascript复制
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.56.101:3306/jdbc
    driver-class-name: com.mysql.cj.jdbc.Driver
    initialization-mode: always
    schema:
      - classpath:department.sql

1.2 department.sql:

代码语言:javascript复制
/*
Navicat MySQL Data Transfer

Source Server         : 本地
Source Server Version : 50528
Source Host           : 127.0.0.1:3306
Source Database       : restful_crud

Target Server Type    : MYSQL
Target Server Version : 50528
File Encoding         : 65001

Date: 2018-03-05 10:41:40
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

1.3 在SpringBoot2.x中,我们需要在配置文件中配置一下:

代码语言:javascript复制
spring.datasource.initialization-mode: always

1.4 启动项目后查看数据库,如下图,确实是创建了department表:

0 人点赞