springboot集成h2

h2数据库是常用的开源数据库,与HSQLDB类似,十分适合作为嵌入式数据库使用,其他的数据库大部分都需要安装独立的客户端和服务器端
 h2的优势:
  (1)h2采用纯java编写,因此不受平台的限制
  (2)h2只有一个jar文件,十分适合作为嵌入式数据库使用
  (3)h2提供了一个十分方便的web控制台用于操作和管理数据库内容。

下面介绍下h2数据库的简单使用

1.添加依赖

创建项目的时候,在数据库选项里直接勾选h2选项,如果是二次项目,在pom文件里添加以下依赖

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

2.连接配置

application.properties 文件(或者 applocation.yml 文件)对数据库进行连接配置

1 spring.datasource.url = jdbc:h2:file:~/.h2/testdb //配置h2数据库连接地址 
2 spring.datasource.driverClassName =org.h2.Driver //配置JDBC Driver
3 spring.datasource.username = sa //配置数据库用户名
4 spring.datasource.password = //配置数据库密码

完成依赖配置和连接配置以后,就可以在项目里使用h2数据库了,Spring会自动完成Datasource的注入,之后无论是用jpa还是mybatis都可以

3.数据初始化配置

如果需要在程序启动时对数据库进行初始化操作,在 application.peoperties 或yml文件里对数据库进行配置

1 spring.datasource.schema=classpath:db/schema.sql   //进行该配置后,每次启动程序,程序都会运行
2 resources/db/schema.sql                            //sql文件,对数据库的结构进行操作。xml文件也行
3 spring.datasource.data=classpath:db/data.sql       //进行该配置后,每次启动程序,程序都会运行    
4 resources/db/data.sql                              //sql文件,对数据库的数据操作。xml文件也行

这个配置十分适合开发环境,最好把数据库结构的构建sql放在 resources/db/schema.sql ,数据sql放在 resources/db/data.sql 中,这样每次
重启项目都可以得到一个新的数据库,这样就不需要每次为了测试而修改数据中的内容了。

4.h2 web consloe

h2 web consloe是一个数据库GUI管理应用,和phpMyAdmin类似,程序运行时,会自动启动h2 web consloe,当然也可以进行如下的配置:

1 spring.h2.console.settings.web-allow-others=true        //进行该配置后,h2 web consloe就可以在远程访问了。否则只能在本机访问。
2 spring.h2.console.path=/h2-console                      //进行该配置,你就可以通过YOUR_URL/h2-console访问h2 web consloe。YOUR_URL是你程序的访问URl。
3 spring.h2.console.enabled=true                   //进行该配置,程序开启时就会启动h2 web consloe。当然这是默认的,如果你不想在启动程序时启动h2 web consloe,那么就设置为false。

配置以后,在浏览器输入 http://localhost:8080/h2-console 然后输入用户名和密码,选择好合适的语言,就可以进入数据库管理应用啦

5.实例

在resource文件下新建包 changelog ,包里包含三个xml文件: changelog.xmldata.xmlinit.xml
其中 changelog.xml 写的是数据库表的结构 , data.xml 文件里写的是数据库表的初始化数据 init.xml 是初始化加载的xml文件,包含前两个xml文件的路径

init.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
2 <databaseChangeLog
3         xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
4         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5         xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">
6     <include file="changeLog.xml" relativeToChangelogFile="true"/>
7     <include file="data.xml" relativeToChangelogFile="true"/>
8 </databaseChangeLog>

changelog.xml 文件:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <databaseChangeLog
 3         xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
 4         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5         xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
 6         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">
 7 
 8     <property name="autoIncrement" value="true" dbms="h2"/>
 9     <changeSet id="init-schema" author="jinzhe"  >
10         <comment>init schema</comment>
11 
12         <createTable tableName="user">
13             <column name="id" type="bigint" autoIncrement="${autoIncrement}">
14                 <constraints primaryKey="true" nullable="false"/>
15             </column>
16             <column name="username" type="varchar(20)" >
17                 <constraints  nullable="false" uniqueConstraintName="username"/>
18             </column>
19             <column name="password" type="varchar(20)">
20                 <constraints  nullable="false"/>
21             </column>
22             <column name="email" type="varchar(20)">
23                 <constraints  nullable="false"/>
24             </column>
25             <column name="phone" type="varchar(11)">
26                 <constraints  nullable="false"/>
27             </column>
28             <column name="sex" type="varchar(2)">
29                 <constraints  nullable="false"/>
30             </column>
31             <column name="creat_time" type="java.util.Date">
32                 <constraints  nullable="false"/>
33             </column>
34             <column name="update_time" type="java.util.Date">
35                 <constraints  nullable="false"/>
36             </column>
37         </createTable>
38     </changeSet>
39 </databaseChangeLog>

data.xml 文件:

1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 2 <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
 3                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4                    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
 5     
 6     <changeSet id="001" author="jin">
 7         
 8         <insert tableName="user" schemaName="public" >
 9             <column name="id" value="1"></column>
10             <column name="username" value="admin123"></column>
11             <column name="password" value="123456"></column>
12             <column name="email" value="165464614@qq.com"></column>
13             <column name="phone" value="15330774444"></column>
14             <column name="sex" value="男"></column>
15             <column name="creat_time" value="2017-12-01 00:00:00"></column>
16             <column name="update_time" value="2017-12-01 00:00:00"></column>
17         </insert>
18 
19     </changeSet>
20 
21 </databaseChangeLog>
在Spring Boot项目中集成H2数据库是一个常见的需求,特别是在开发和测试阶段。H2数据库是一个轻量级的嵌入式数据库,它支持内存模式和持久化模式,非常适合快速开发和原型设计。 ### 添加Maven依赖 首先,在`pom.xml`文件中添加H2数据库的依赖项。如果你使用的是Spring Initializr生成的项目,并且已经选择了H2数据库作为依赖,那么这个步骤可能已经完成。如果没有,请手动添加以下依赖: ```xml <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> ``` 同时,确保你有一个Spring Data JPA的依赖,因为它是用来与H2数据库交互的关键组件之一: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` ### 配置数据源 接下来,你需要配置Spring Boot以使用H2数据库。这通常通过`application.properties`或`application.yml`文件来完成。 #### 使用 `application.properties` 在`src/main/resources/application.properties`文件中添加以下配置: ```properties spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true ``` - `spring.datasource.url`: 指定H2数据库的URL。这里使用的是内存模式(`mem:testdb`),并且设置了`DB_CLOSE_DELAY=-1`以防止数据库在最后一个连接关闭时自动关闭。 - `spring.datasource.driver-class-name`: 指定H2数据库的驱动类名。 - `spring.datasource.username` 和 `spring.datasource.password`: H2数据库的默认用户名为`sa`,密码为空。 - `spring.jpa.hibernate.ddl-auto`: 设置为`update`表示Hibernate会根据实体类自动更新数据库结构。 - `spring.jpa.show-sql`: 显示执行的SQL语句。 - `spring.jpa.properties.hibernate.format_sql`: 格式化显示的SQL语句。 #### 使用 `application.yml` 如果你更喜欢使用YAML格式,可以在`src/main/resources/application.yml`文件中添加以下配置: ```yaml spring: datasource: url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE driver-class-name: org.h2.Driver username: sa password: jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate: format_sql: true ``` ### 启用H2控制台 为了方便调试和查看数据库内容,Spring Boot提供了H2数据库的Web控制台。你可以通过以下步骤启用它: 1. **添加H2控制台依赖**(如果尚未添加): ```xml <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> ``` 2. **配置H2控制台**:在`application.properties`或`application.yml`中添加以下配置: ```properties spring.h2.console.enabled=true spring.h2.console.path=/h2-console ``` 或者在`application.yml`中: ```yaml spring: h2: console: enabled: true path: /h2-console ``` 3. **访问H2控制台**:启动应用程序后,打开浏览器并访问`http://localhost:8080/h2-console`。输入JDBC URL、用户名和密码(默认为`sa`和空密码),然后点击“Connect”即可进入H2数据库的Web控制台。 ### 创建实体类和Repository 为了验证H2数据库是否正确集成,可以创建一个简单的实体类和对应的Repository接口。 #### 实体类 ```java import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // Getters and Setters } ``` #### Repository接口 ```java import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { } ``` #### 测试控制器 创建一个简单的REST控制器来测试数据库操作: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping public List<User> getAllUsers() { return userRepository.findAll(); } @PostMapping public User createUser(@RequestBody User user) { return userRepository.save(user); } } ``` ### 测试集成 启动应用程序后,可以通过发送HTTP请求来测试数据库操作。例如,使用Postman或curl命令创建用户并检索所有用户。 #### 创建用户 ```bash curl -X POST http://localhost:8080/users -H "Content-Type: application/json" -d '{"name":"John Doe","email":"john@example.com"}' ``` #### 获取所有用户 ```bash curl http://localhost:8080/users ``` ### 总结 通过以上步骤,你已经成功地在Spring Boot项目中集成了H2数据库。H2数据库不仅易于配置,而且非常适合开发和测试环境。如果你需要在生产环境中使用更强大的数据库(如MySQL或PostgreSQL),可以轻松替换掉H2数据库的依赖和配置[^1]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值