Spring Boot 整合使用 H2 内存数据库
1、概览 本文将带你了解如何在 Spring Boot 中使用 H2 内存数据库。与其他数据库一样,Spring Boot 生态系统对 H2 提供了开箱即用的支持。
2、依赖 添加 h2 和 spring-boot-starter-data-jpa 依赖:
<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> 3、Datasource 配置 默认情况下,Spring Boot 会配置应用使用用户名 sa 和空密码连接到内存数据库。
不过,你也可以通过在 application.properties 文件中添加以下属性来更改这些参数:
spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect 相应的 YAML 配置如下:
spring: datasource: url: jdbc:h2:mem:mydb username: sa password: password driverClassName: org.h2.Driver jpa: spring.jpa.database-platform: org.hibernate.dialect.H2Dialect 内存数据库会在应用重启后会丢失数据,可以通过使用基于文件的存储来改变这种行为。
更新 spring.datasource.url 属性:
spring.datasource.url=jdbc:h2:file:/data/demo 相应的 YAML 配置如下:
spring: datasource: url: jdbc:h2:file:/data/demo H2 数据库还可以在 其他模式 下运行。