起因
最近闲来无事突发奇想写了一个并发小工具,涉及了spring事务管理,所以需要一个简单的数据库支持,就想起了H2这个内存数据库,由此记录一下。
依赖引入
首先单元测试要有junit支持,因为要用h2所以引入了H2。
再有就是spring相关的必须依赖了:spring-context启动spring环境用;spring-tx使用spring事务;spring-jdbc数据库连接。
因为是仅用于单元测试,所以很多依赖的scope都是test级别。
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
文件目录
因为这个地方使用spring就是为了进行单元测试,所以配置文件等都写在了test文件夹下。
spring配置文件
因为是简单项目测试,就没有使用spring-boot,需要手写一下spring的配置文件。
这里需要引入jdbc、tx两个命名空间,所以要保证对应的依赖已经被添加进来。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<!-- 引入h2作为datasource -->
<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="classpath:db-schema.sql"/>
<jdbc:script location="classpath:db-test-data.sql"/>
</jdbc:embedded-database>
<!-- 被测试的类对象,作为一个普通bean注入spring容器,其中对数据库的操作直接使用jdbcTemplate实现 -->
<bean id="testBean" class="com.btm.planb.parallel.thread.transaction.TestBean">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 数据库事物管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 开始注解事物 -->
<tx:annotation-driven/>
</beans>
在spring配置文件中配置datasource时,配置了两个jdbc script脚本文件,这两个文件中db-shcema.sql是用来初始化表的,立main都是create table语句,另一个db-test-data.sql是用来往数据库中写入基础测试数据的,里面用到的表一定是在db-schema.sql中创建好的表,不然sql会报错。而且这两个文件中一定要有内容,不能是空的,空文件也报错。
测试
剩下的就是正常写单元测试类了。具体可以直接参考项目:https://gitee.com/BigTailMonkey/plan-b/tree/master/parallel-thread-transaction 中的单元测试类。