2、然后再次测试普通的sqlSession,发现日志内容中虽然插入了1000条数据,但只新建了一次连接,最后又关闭了该连接(日志如下)。也就是说MyBatis中的普通sqlSession好像已经对批量插入默认是一次连接中完成,那么还提供ExecutorType.BATCH方式干什么,况且该方式好像效率也不行,或者是我使用ExecutorType.BATCH方式不对??
- DEBUG [main] - Created connection 3502256.
- DEBUG [main] - ooo Connection Opened
- DEBUG [main] - ==> Executing: insert into student ( name, sex, address, telephone, t_id ) values ( ?, ?, ?, ?, ? )
- DEBUG [main] - ==> Parameters: 新人0(String), male(String), addr0(String), dd(String), 3(Integer)
- DEBUG [main] - ==> Executing: insert into student ( name, sex, address, telephone, t_id ) values ( ?, ?, ?, ?, ? )
- DEBUG [main] - ==> Parameters: 新人1(String), male(String),
- ...............
- ...............
- DEBUG [main] - xxx Connection Closed
- DEBUG [main] - Returned connection 3502256 to pool.
3、最后一点是关于数据库批量插入时sql语句级的优化,我特意测试了两种方式,在StudentMapper中配置了两种insert模式。第一种对应insert value1,insert value2,,,,;第二种对应insert values (value1, value2,....)。发现后者果然比前者快很多啊。下面是两种insert模式,及测试结果对应图:
- <!-- 在外部for循环调用一千次 -->
- <insert id="insert" parameterType="sdc.mybatis.test.Student">
- insert into student (id, name, sex,
- address, telephone, t_id
- )
- values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR},
- #{sex,jdbcType=VARCHAR},
- #{address,jdbcType=VARCHAR}, #{telephone,jdbcType=VARCHAR}, #{tId,jdbcType=INTEGER}
- )
- </insert>
- <!-- 批量 ,传入一个长度为1000的list -->
- <insert id="insertBatch" >
- insert into student ( <include refid="Base_Column_List" /> )
- values
- <foreach collection="list" item="item" index="index" separator=",">
- (null,#{item.name},#{item.sex},#{item.address},#{item.telephone},#{item.tId})
- </foreach>
- </insert>
附录:
- MyBatis配置文件的DTD文件(与Ibatis3不同):http://mybatis.org/dtd/
- MyBatis的中文手册:http://mybatis.googlecode.com/files/MyBatis%203%20User%20Guide%20Simplified%20Chinese.pdf
