H2数据库做单测数据库时踩到的坑
H2数据库用来做单测数据库,可以自定义初始化数据,不用担心数据库内容更改造成单测跑不过问题,不过H2数据库跟实际使用的Mysql还是有一定区别。
1. H2数据库不支持Mysql的批量更新功能,支持批量插入
--批量更新(H2不支持) <update id="increaseBatch" parameterType="java.util.List"> <foreach collection="list" item="item" index="index" open="" close="" separator=";"> update product <set> quantity = quantity + #{item.updateQuantity}, modify_time = #{item.modifyTime} </set> where id = #{item.productId} </foreach> </update> --批量插入(H2支持) <insert id="insertItems" keyProperty="id" parameterType="java.util.List" useGeneratedKeys="true"> <selectKey keyProperty="id" order="AFTER" resultType="long"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO bill_item( bill_id,product_id,product_name,product_quantity,product_quantity_after,product_price,product_amount) VALUES <foreach close="" collection="list" index="index" item="item" open="" separator=","> ( #{item.billId},#{item.productId},#{item.productName},#{item.productQuantity}, #{item.productQuantityAfter},#{item.productPrice},#{item.productAmount}) </foreach> </insert>
2. H2数据库不支持Mysql的replace into 语法
3. H2数据库初始化时不允许出现相同的UK
<jdbc:embedded-database id="dataSource" type="H2"> <jdbc:script location="classpath:H2_TYPE.sql"/> <jdbc:script location="classpath:INIT_TABLE.sql"/> <jdbc:script location="classpath:INIT_DATA.sql"/> </jdbc:embedded-database>
INIT_TABLE.sql
-- 表A CREATE TABLE `table_A` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `bill_no` varchar(45) DEFAULT NULL COMMENT '单号', `bill_type` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT '单据类别', `created_time` datetime NOT NULL DEFAULT '1000-01-01 00:00:00' COMMENT '创建时间', `modify_time` datetime NOT NULL DEFAULT '1000-01-01 00:00:00' COMMENT '修改时间', PRIMARY KEY (`id`), UNIQUE KEY `uk_bill_type_bill_no` (`bill_type`,`bill_no`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ; --表A CREATE TABLE `table_B` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `bill_no` varchar(45) DEFAULT NULL COMMENT '单号', `bill_type` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT '单据类别', `created_time` datetime NOT NULL DEFAULT '1000-01-01 00:00:00' COMMENT '创建时间', `modify_time` datetime NOT NULL DEFAULT '1000-01-01 00:00:00' COMMENT '修改时间', PRIMARY KEY (`id`), UNIQUE KEY `uk_bill_type_bill_no` (`bill_type`,`bill_no`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
运行结果:
Caused by: org.h2.jdbc.JdbcSQLException: Constraint "uk_bill_type_bill_no" already exists; SQL statement:CREATE TABLE `table_B` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键', `bill_no` varchar(45) DEFAULT NULL COMMENT '单号', `bill_type` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT '单据类别', `created_time` datetime NOT NULL DEFAULT '1000-01-01 00:00:00' COMMENT '创建时间', `modify_time` datetime NOT NULL DEFAULT '1000-01-01 00:00:00' COMMENT '修改时间', PRIMARY KEY (`id`), UNIQUE KEY `uk_bill_type_bill_no` (`bill_type`,`bill_no`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;