欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > springboot整合h2

springboot整合h2

2025/5/24 14:51:46 来源:https://blog.csdn.net/qq_37069064/article/details/145083410  浏览:    关键词:springboot整合h2

在 Spring Boot 中整合 H2 数据库非常简单。H2 是一个轻量级的嵌入式数据库,非常适合开发和测试环境。以下是整合 H2 数据库的步骤:

1. 添加依赖

首先,在你的 pom.xml 文件中添加 H2 数据库的依赖:

<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope>
</dependency>

2. 配置 H2 数据库

在 application.properties 或 application.yml 文件中配置 H2 数据库的相关参数:

# 启用 H2 控制台
spring.h2.console.enabled=true# H2 数据库的 JDBC URL
spring.datasource.url=jdbc:h2:mem:testdb# 数据库用户名和密码
spring.datasource.username=sa
spring.datasource.password=123456# 数据库驱动类
spring.datasource.driver-class-name=org.h2.Driver# 数据库初始化脚本(可选)
spring.datasource.schema=classpath:schema.sql
spring.datasource.data=classpath:data.sql

spring:h2:console:enabled: truedatasource:url: jdbc:h2:mem:testdbdriver-class-name: org.h2.Driverusername: sapassword: 123456

3. 创建数据库初始化脚本(可选)

在 src/main/resources 目录下创建 schema.sql 和 data.sql 文件,用于初始化数据库表结构和数据。例如:

schema.sql:

CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(100) NOT NULL,email VARCHAR(100) NOT NULL
);

data.sql:

INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com');
INSERT INTO users (name, email) VALUES ('Jane Doe', 'jane@example.com');

4. 使用 H2 控制台

启动应用程序后,你可以通过访问 http://localhost:8080/h2-console 来使用 H2 控制台。在登录页面中,输入你在 application.properties 中配置的 JDBC URL、用户名和密码,然后点击连接即可。

http://localhost:8080/h2-console

5.页面客户端连接测试

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词