第一种,用batch模式
<update id="updateTest" > update t_test set status = status where test_id = #{testId} </update>
public void updateBatch2() throws Exception { long start = System.currentTimeMillis(); SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false); TestDao mapper = sqlSession.getMapper(TestDao.class); List<TestEntity> list = testDao.queryList(null); for (TestEntity testEntity :list) { mapper.updateTest(testEntity.getTestId()); } sqlSession.commit(); long end = System.currentTimeMillis(); System.out.println("---------------" + (start - end) + "---------------"); }
第二种,用foreach
<update id="updateTestBatch" parameterType="java.util.List"> <foreach collection="testIds" item="item" index="index" open="" close="" separator=";" > update t_test set status = status where test_id = #{item} </foreach> </update>
public void updateBatch2() throws Exception { long start = System.currentTimeMillis(); List<TestEntity> list = testDao.queryCaseList(null); List<String> idList = Lists.newArrayList(); for (TestEntity testEntity :list) { idList.add(testEntity.getTestId()); } testDao.updateTestBatch(idList); long end = System.currentTimeMillis(); System.out.println("---------------" + (start - end) + "---------------"); }
第一轮:
第一种耗时:1546,第二种耗时:359
第二轮:
第一种耗时:1103,第二种耗时:445
第三轮:
第一种耗时:1105,第二种耗时:554
在不考虑sql语句太长的情况下,第二种效率会好点,mysql的sql语句大小不起过1M(PS:但这个修改),具体原因可能是allowMultiQueries这个参数,告诉mysql执行多个sql语句,没加这个参数时,foreach是会报错