1.批量插入
mybatis通过foreach循环拼接好sql语句。
第一种
如果传入的是单参数且参数类型是一个List的时候
@Override
public void insertCommunityPoiBatch(List<PageData> list) {
try {
dao.save("ClCommunityPoiMapper.insertCommunityPoiBatch", list);
} catch (Exception e) {
logger.error(e.toString(), e);
}
}
<insert id="insertCommunityPoiBatch" parameterType="java.util.List">
INSERT INTO cl_community_poi (
id,
poi_id,
community_id,
poi_name
) VALUES
<foreach collection="list" index="index" item="item" separator=",">
(#{item.id},
#{item.poiId},
#{item.communityId}
)
</foreach>
</insert>
第二种
如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map
PageData是内部封装的,相当于一个Map
@Override
public void insertClAdArrangedConditionMutexBatch(PageData pageData) {
try {
dao.update("ClAdArrangedConditionMapper.insertClAdArrangedConditionMutexBatch", pageData);
} catch (Exception e) {
logger.error(e.toString(), e);
}
}
<insert id="insertClAdArrangedConditionMutexBatch" parameterType="pd">
insert into cl_ad_arranged_condition_mutex
(mutex_id,condition_id,mutex_type,mutex_condition_id)
values
<foreach collection="conditionMutexList" item="item" index="index" separator=",">
(#{item.mutexId},#{item.conditionId},#{item.mutexType},#{item.mutexConditionId})
</foreach>
</insert>
2.批量更新
第一种
需要在db链接url后面带一个参数 &allowMultiQueries=true
即: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&allowMultiQueries=true
如果传入的是单参数且参数类型是一个List的时候
@Override
public int updPptTemplateElementBatch(List<PageData> list) {
int i = 0;
try {
i = (int) dao.update("SupplierOrderMapper.updPptTemplateElementBatch", list);
} catch (Exception e) {
logger.error(e.toString(), e);
}
return i;
}
<update id="updPptTemplateElementBatch" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update install_ppt_template_element
<set >
<if test="item.elementCode != null" >
element_code = #{item.elementCode,jdbcType=VARCHAR},
</if>
<if test="item.elementName != null" >
element_name = #{item.elementName,jdbcType=VARCHAR},
</if>
</set>
where template_id = #{item.templateId,jdbcType=VARCHAR}
</foreach>
</update>