赞
踩
tk.mybatis没有带批量更新的功能,批量更新却是经常使用的,所以需要自己实现。
批量更新网上主要有2种方式:case when方式、foreach方式
但是foreachzhe这种方式效率非常低下,不知道为何那多么帖子在流传,请看我另一个文章。
扩展tk.mybatis的批量更新,采用case when方式,源码干货如下:
import org.apache.ibatis.annotations.UpdateProvider; import java.util.List; /** * 批量update * * @param <T> 不能为空 */ @tk.mybatis.mapper.annotation.RegisterMapper public interface UpdateBatchByPrimaryKeySelectiveMapper<T> { /** * 根据Example条件批量更新实体`record`包含的不是null的属性值 * * @return */ @UpdateProvider(type = BatchExampleProvider.class, method = "dynamicSQL") int updateBatchByPrimaryKeySelective(List<? extends T> recordList); }
import org.apache.ibatis.mapping.MappedStatement; import tk.mybatis.mapper.entity.EntityColumn; import tk.mybatis.mapper.mapperhelper.EntityHelper; import tk.mybatis.mapper.mapperhelper.MapperHelper; import tk.mybatis.mapper.mapperhelper.SqlHelper; import tk.mybatis.mapper.provider.ExampleProvider; import java.util.Set; /** * 批量更新的SqlProvider * @author sunchangtan */ public class BatchExampleProvider extends ExampleProvider { public BatchExampleProvider(Class<?> mapperClass, MapperHelper mapperHelper) { super(mapperClass, mapperHelper); } /** * 拼update sql, 使用case when方式,id为主键 * * @param ms * @return */ public String updateBatchByPrimaryKeySelective(MappedStatement ms) { final Class<?> entityClass = getEntityClass(ms); //开始拼sql StringBuilder sql = new StringBuilder(); sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass))); sql.append("<trim prefix=\"set\" suffixOverrides=\",\">"); //获取全部列 Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass); for (EntityColumn column : columnList) { if (!column.isId() && column.isUpdatable()) { sql.append(" <trim prefix=\""+column.getColumn()+" =case\" suffix=\"end,\">"); sql.append(" <foreach collection=\"list\" item=\"i\" index=\"index\">"); sql.append(" <if test=\"i."+column.getEntityField().getName()+"!=null\">"); sql.append(" when id=#{i.id} then #{i."+column.getEntityField().getName()+"}"); sql.append(" </if>"); sql.append(" </foreach>"); sql.append(" </trim>"); } } sql.append("</trim>"); sql.append("WHERE"); sql.append(" id IN "); sql.append("<trim prefix=\"(\" suffix=\")\">"); sql.append("<foreach collection=\"list\" separator=\", \" item=\"i\" index=\"index\" >"); sql.append("#{i.id}"); sql.append("</foreach>"); sql.append("</trim>"); return sql.toString(); } }
/**
* 批量操作接口
*
* @param <T>
* @author sunchangtan
*/
@tk.mybatis.mapper.annotation.RegisterMapper
public interface BatchMapper<T> extends
UpdateBatchByPrimaryKeySelectiveMapper<T> {
}
List<List<BatchTest>> splitList = ListUtils.splitList(list, 100);
splitList.forEach(data -> {
batchTestMapper.updateBatchByPrimaryKeySelective(data);
});
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。