mybatis批量新增、删除、查询和修改

 每次写批量的时候,都要在网上搜索一下,虽然都做过多次了,但具体的自己还是记不住(汗颜),所以索性今天就记录下来。

  前期说明:     

     foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有 item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:

1.     如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2.     如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

3.     如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在breast里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key

http://blog.sina.com.cn/s/blog_6a0cd5e501011snl.html


(1)mybatis批量新增

mapper.xml

<insert id="createBatchUserInfoList" useGeneratedKeys="true" parameterType="java.util.List" >
        insert into
            el_user_info (id,user_name,user_tel,pass_word,user_sex,del_mark,position_id,agency_id,create_date,update_date,role_id,employee_id,org_id)
        values
        <foreach collection="list" item="item" index="index" separator="," >
            (#{item.id},#{item.userName},#{item.userTel}, #{item.passWord},#{item.userSex},
             #{item.delMark},#{item.positionId},#{item.agencyId},#{item.createDate},#{item.updateDate},#{item.roleId},#{item.employeeId},#{item.orgId})
        </foreach>
    </insert>

mapper:

/**
     * 批量插入
     *
     * @param list
     * @return
     */
    int createBatchUserInfoList(List<ElUserInfo> list);

serviceImpl实现类:

try {
            List<ElUserInfo>  userList = new ArrayList<ElUserInfo>();
            if (CollectionUtils.isNotEmpty(list)) {
                //组织id
                Long orgId = elAppInfoService.getOrg().getOrgId();
                for (int i = 0; i < list.size(); i++) {
                    Map<String, Object> map = list.get(i);
                    String userSex = map.get("userSex").toString().trim();
                    String userName = map.get("userName").toString().trim();
                    String userTel = map.get("userTel").toString().trim();
                    String key = userName + userTel;

                    String redisCacheByKey = redisCacheService.getRedisCacheByKey(key);
                    log.info(redisCacheByKey);
                    if (!StringUtils.isEmpty(redisCacheByKey)) {
                       //redisCacheService.deleteRedisCacheByKey(key);
                            continue;
                    }
                    if ("男".equals(userSex)) {
                        userSex = "0";
                    } else if ("女".equals(userSex)){
                        userSex = "1";
                    }
                    ElUserInfo user = new ElUserInfo();
                    user.setUserName(userName);
                    user.setUserTel(userTel);
                    user.setPassWord(MD5(map.get("passWord").toString().trim()));
                    user.setUserSex(userSex);
                    user.setPositionId(postionId);
                    user.setAgencyId(agencyId);
                    user.setCreateDate(new Date());
                    user.setUpdateDate(new Date());
                    user.setDelMark(0);
                    user.setRoleId(1L);
                    user.setEmployeeId(0L);
                    user.setOrgId(orgId);
                    userList.add(user);
                }
                if (CollectionUtils.isNotEmpty(userList)) {
                    //先持久化本地
                    row = userInfoMapper.createBatchUserInfoList(userList);
                    if (row > 0) {
                        //持久化成功后同步组织平台
                        String add = orgEmployeeService.addOrganRoleUserToPlatform(userList, "add");
                        if (!StringUtils.isEmpty(add) && !"-1".equals(add) && !"null".equals(add)) {
                            //以用户手机号码为唯一标示,批量修改OrgId和EmployeeId
                            userInfoMapper.updateBatchOrgId(userList);
                        }
                        log.info(this.getClass().getName()+"的UserInfoThread"+add.toString());
                    }
                }
            }
        } catch (Exception e) {
            log.error("elPositionInfoServiceImpl的UserInfoThread方法error"+e.getMessage(),e);
        }

(2)mybatis批量删除

mapper.xml:

<delete id="batchDeleteUser">
        delete from t_user where id in (
        <foreach collection="ids" item="id" separator=",">
            #{id}
        </foreach>
        )  
 </delete>
<!-- 第二种批量删除的写法 -->
<!-- open表示该语句以什么开始,close表示以什么结束 -->
<delete id="">
        delete from t_user where id in 
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
</delete>

mapper:

int batchDeleteUser(int[] ids);

(3)mybatis批量查询

mapper.xml:

 <select id="getPostionListIdsByRoleCode" resultType="com.xxx.bean.ElPositionInfo" parameterType="java.util.List">
    select
          <include refid="Base_Column_List" />
    from el_position_info
    where roleCode in
    <foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
         #{item.roleCode}
    </foreach>
  </select>

mapper:

List<ElPositionInfo> getPostionListIdsByRoleCode(List<ElPositionInfo> list);

(4)mybatis批量修改

请访问我之前写的一篇文章:

https://mp.csdn.net/postedit/78403399

猜你喜欢

转载自blog.csdn.net/xuforeverlove/article/details/80743625