Mybatis批量更新三种方式

5次阅读

共计 2425 个字符,预计需要花费 7 分钟才能阅读完成。

Mybatis 实现批量更新操作方式一:
<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 这个才可以执行。方式二:
<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, 但无法返回受影响数量。
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 执行,不太安全方式二 当数据量大的时候,效率明显降低方式三 需要自己控制,自己处理,一些隐藏的问题无法发现。
附件: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;
}
}
}

正文完
 0