Mybatis實現批量更新操做
方式一:java
<update id="updateBatch" parameterType="java.util.List"> <foreach collection="list" item="item" index="index" open="" close="" separator=";"> update tableName <set> name=${item.name}, name2=${item.name2} </set> where id = ${item.id} </foreach> </update>
但Mybatis映射文件中的sql語句默認是不支持以" ; " 結尾的,也就是不支持多條sql語句的執行。因此須要在鏈接mysql的url上加 &allowMultiQueries=true 這個才能夠執行。
方式二:mysql
<update id="updateBatch" parameterType="java.util.List"> update tableName <trim prefix="set" suffixOverrides=","> <trim prefix="c_name =case" suffix="end,"> <foreach collection="list" item="cus"> <if test="cus.name!=null"> when id=#{cus.id} then #{cus.name} </if> </foreach> </trim> <trim prefix="c_age =case" suffix="end,"> <foreach collection="list" item="cus"> <if test="cus.age!=null"> when id=#{cus.id} then #{cus.age} </if> </foreach> </trim> </trim> <where> <foreach collection="list" separator="or" item="cus"> id = #{cus.id} </foreach> </where> </update>
這種方式貌似效率不高,可是能夠實現,並且不用改動mysql鏈接
效率參考文章:https://blog.csdn.net/xu19166...
方式三:
臨時改表sqlSessionFactory的屬性,實現批量提交的java,但沒法返回受影響數量。spring
public int updateBatch(List<Object> list){ if(list ==null || list.size() <= 0){ return -1; } SqlSessionFactory sqlSessionFactory = SpringContextUtil.getBean("sqlSessionFactory"); SqlSession sqlSession = null; try { sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false); Mapper mapper = sqlSession.getMapper(Mapper.class); int batchCount = 1000;//提交數量,到達這個數量就提交 for (int index = 0; index < list.size(); index++) { Object obj = list.get(index); mapper.updateInfo(obj); if(index != 0 && index%batchCount == 0){ sqlSession.commit(); } } sqlSession.commit(); return 0; }catch (Exception e){ sqlSession.rollback(); return -2; }finally { if(sqlSession != null){ sqlSession.close(); } } }
其中 SpringContextUtil 是本身定義的工具類 用來獲取spring加載的bean對象,其中getBean() 得到的是想要獲得的sqlSessionFactory。Mapper 是本身的更具業務需求的Mapper接口類,Object是對象。
總結
方式一 須要修改mysql的鏈接url,讓全局支持多sql執行,不太安全
方式二 當數據量大的時候 ,效率明顯下降
方式三 須要本身控制,本身處理,一些隱藏的問題沒法發現。sql
附件:SpringContextUtil.java安全
@Component public class SpringContextUtil implements ApplicationContextAware{ private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext(){ return applicationContext; } public static Object getBean(Class T){ try { return applicationContext.getBean(T); }catch (BeansException e){ return null; } } public static Object getBean(String name){ try { return applicationContext.getBean(name); }catch (BeansException e){ return null; } } }