spring boot2X使用schema.sql初始化数据库

spring boot 版本

2.2.5.RELEASE

初始化文件 schema.sql 放在项目resources下

复制代码
drop table users if exists;
drop table goods if exists;

create table users (
    id bigint auto_increment,
    name varchar(255),
    create_time timestamp,
    primary key (id)
);

create table goods (
  id bigint auto_increment,
  name varchar(255),
  price bigint,
  create_time timestamp,
  update_time timestamp,
  primary key (id)
);

insert into users (name, create_time) values ('Lili', now());
insert into users (name, create_time) values ('Fiona', now());

insert into goods (name, price, create_time, update_time) values ('bag', 2000, now(), now());
insert into goods (name, price, create_time, update_time) values ('bottole', 2500, now(), now());
复制代码

数据库H2

依赖

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
复制代码

配置

复制代码
spring.jpa.database=h2
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.open-in-view=false
spring.datasource.url=jdbc:h2:./data/test
spring.datasource.username=sa
spring.datasource.password=123456
spring.datasource.driverClassName=org.h2.Driver
spring.h2.console.path=/h2-console
spring.h2.console.enabled=true
复制代码

启动项目,数据库会按照schema.sql 进行初始化

说明:

  spring.datasource.initialization-mode 的值默认为 embedded

  如果要在mysql下执行需要设置

    spring.datasource.initialization-mode=always

posted @   慕尘  阅读(1404)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2018-03-27 hexo的搭建
点击右上角即可分享
微信分享提示