在Spring Boot使用H2内存数据库git
在以前的文章中咱们有提到在Spring Boot中使用H2内存数据库方便开发和测试。本文咱们将会提供一些更加具体有用的信息来方便咱们使用H2数据库。github
要想使用H2,咱们须要添加以下配置:web
<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 Boot会为咱们自动建立内存H2数据库,方便咱们使用,固然咱们也能够使用本身的配置,咱们将配置写入application.properties:spring
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
默认状况下内存数据库会在程序结束以后被销毁,若是咱们想永久保存内存数据库须要添加以下配置:sql
spring.datasource.url=jdbc:h2:file:/data/demo
这里配置的是数据库的文件存储地址。数据库
咱们能够在resources文件中添加data.sql 文件,用来在程序启动时,建立所需的数据库:springboot
DROP TABLE IF EXISTS billionaires; CREATE TABLE billionaires ( id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(250) NOT NULL, last_name VARCHAR(250) NOT NULL, career VARCHAR(250) DEFAULT NULL ); INSERT INTO billionaires (first_name, last_name, career) VALUES ('Aliko', 'Dangote', 'Billionaire Industrialist'), ('Bill', 'Gates', 'Billionaire Tech Entrepreneur'), ('Folrunsho', 'Alakija', 'Billionaire Oil Magnate');
Spring Boot在启动时候会自动加载data.sql文件。这种方式很是方便咱们用来测试。app
虽然是一个内存数据库,咱们也能够在外部访问和管理H2,H2提供了一个内嵌的GUI管理程序,咱们看下怎么使用。首先须要添加以下权限:spring-boot
spring.h2.console.enabled=true
启动程序, 咱们访问 http://localhost:8080/h2-console ,获得以下界面:测试
记得填入你在配置文件中配置的地址和密码。
登陆以后,咱们能够看到以下的管理界面:
咱们还能够添加以下配置来管理这个GUI:
spring.h2.console.path=/h2-console spring.h2.console.settings.trace=false spring.h2.console.settings.web-allow-others=false
其中path指定了路径,trace指定是否开启trace output,web-allow-others指定是否容许远程登陆。
本文的例子能够参考https://github.com/ddean2009/learn-springboot2/tree/master/springboot-h2