您的位置:首页 > 数据库 > MySQL

MYBATIS+MYSQL 批量操作数据库

2017-10-25 10:38 411 查看
批量操作数据库可减少数据库连接次数,大大提高运行速率。

一、批量插入:

Mapper.xml

<insert id="insertList" useGeneratedKeys="true" parameterType="java.util.List" >
insert into tableA (parent_category, category, cate_type, parent_cate_id, cate_id)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.parentCategory},#{item.category},#{item.cateType},
#{item.parentCateId},#{item.cateId})
</foreach>
</insert>


Mapper.java

int insertList(List<EntryA> list);


二、批量筛选

Mapper.xml

<select id="selectByPrimaryKeyList" resultMap="BaseResultMap" >
select
<include refid="Base_Column_List" />
from case_description where id in(
<foreach item="item" index="index" collection="list" separator=",">
#{item}
</foreach>)
</select>


Mapper.java

List<BaseResultMap> selectByPrimaryKeyList(List<Integer> list);


三、多参数批量筛选

Mapper.xml

<select id="selectByMap" parameterType="java.util.Map"  resultType="java.lang.Integer">
SELECT desc_id from tableA
where
subtask_id=#{subTaskId,jdbcType=INTEGER}
and
desc_id in(
<foreach collection="list" item="item" index="index" separator=",">
#{item}
</foreach>
)
</select>


Mapper.java

List<Integer> selectByMap(Map<String, Object> map);


Service略

在Controller中组装Map

Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
paramMap.put("subTaskId", subtaskid);
paramMap.put("list", idList);


四、批量更新

Mapper.xml

<update id="updateByList"  parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update tableA
<set>
cate_id=#{item.cateId}
</set>
where app_id = #{item.appId}
</foreach>
</update>


Mapper.java

Integer updateByList(List<EntryA> list);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql mybatis 数据库