springMVC 接收數組參數,mybatis 接收數組參數,mybatis批量插入/批量刪除案例


案例是給一個用戶賦予多個權限,多個權限用其對應的主鍵 id 為參數,組成了 一個id數組,傳給springMVC,然后springMVC傳給mybatis,然后mybatis批量插入。其實類似的場景還有批量刪除多個,也是類似的。

1. 前台頁面

        <thead><tr><th>權限選擇</th><th>name</th><th>permission</th></tr></thead>
                  <c:forEach var="priv" items="${list }">
                       <tr class="odd gradeX">
                      <td><input type="checkbox" name="priv_id" value="${priv.id}" /></td>
                      <td><c:out value="${priv.name}"/></td>
                      <td><c:out value="${priv.permission}"/></td>
                    </tr>
                  </c:forEach>

2. jquery獲得選中的項的id值:

            //jquery獲取復選框值    
            var priv_ids =[];//定義一個數組    
            $('input[name="priv_id"]:checked').each(function(){    // 遍歷每一個name為priv_id的復選框,其中選中的執行函數    
                priv_ids.push($.trim($(this).val()));    // 將選中的值添加到數組priv_ids中    
            });
            console.log(priv_ids);
            var indata = {userId:user_id, privIds:priv_ids};
            $.post("/ems/priv/setPrivilege", indata, function(data){
                if(data != null && data.result == 'ok'){
                    console.log(data.msg);
                    alert(data.msg);
                }else{
                    alert(data.msg);
                }
            }, 'json');

提交的json格式的數據:var indata = {userId:user_id, privIds:priv_ids};

其中的 priv_ids 是一個有 id 組成的數組。

3. springMVC接收數組參數:

    @RequestMapping(value="/setPrivilege")
    @ResponseBody
    public void setPrivilege(@RequestParam(value = "privIds[]") Integer[] privIds, Integer userId, PrintWriter writer){
        int result = this.privilegeService.setPrivilegeForUser(privIds, userId);
        Map<String, String> map = new HashMap<>();
        if(result > 0){
            map.put("result", "ok");
            map.put("msg", "設置成功");
            writer.write(JSON.toJSONString(map));
        }
    }

我們看到使用了:@RequestParam(value = "privIds[]") Integer[] privIds 來獲取前台傳來的數組參數。

springMVC接收參數時,最好不要使用 int, long等原始類型,而應該使用它們對應的包裝類型,不然當傳入的參數為空時,會報錯,而包裝類型可以使用null表示傳入的空值。

4. service層的處理,很簡單,直接使用map向mybatis傳遞參數:

@Service("privilegeService")
@Transactional
public class PrivilegeServiceImpl implements PrivilegeService {
    @Autowired
    private PrivilegeMapper privilegeMapper;

    @Override
    @Transactional(readOnly=true)
    public List<Privilege> getAllPrivilege() {
        return privilegeMapper.getAllPrivilege();
    }

    @Override
    public int setPrivilegeForUser(Integer[] privIds, Integer userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("privIds", privIds);
        map.put("userId", userId);
        return this.privilegeMapper.setPrivilegeForUser(map);
    }
}

5. 最后看 mybatis 的 xml 中的sql如何寫:

  <insert id="setPrivilegeForUser" parameterType="map">
      insert into user_privilege(user_id, privilege_id) values 
      <foreach collection="privIds" index="index" item="item" separator=",">
          ( #{userId}, #{item} )
      </foreach>
  </insert>

我們看到使用了 foreach 來循環傳遞進來的數組 privIds,最后組成的sql語句如下所示:

insert into user_privilege(user_id, privilege_id) values (3, 1),(3,2),(33),(3,4) 

user_id 不變,而privilege_id 是數組 privIds 中的循環出來的 id 值。其實就是數據庫的批量插入。

6. 批量刪除多個的處理

刪除時,和前面批量插入處理也是極其類似的,只在最后mybatis中xml中sql的寫法有點區別:

  <delete id="deleteByIds" parameterType="java.util.List">
      delete from user_privilege where id in
      <foreach collection="list" index="index" item="item" open="(" separator="," close=")">   
        #{item}   
      </foreach>  
  </delete>

比較批量刪除和批量插入,可以看出 foreach 中的 open="(" 和 close=")" 只在循環的開始和結束會加上,而 separator="," 是每循環一次,就加一次逗號

7. 批量插入傳入對象List的例子:

<insert id="batchInsertStudent" parameterType="java.util.List">  
    insert into student (id,name,sex,tel,address) values
    <foreach collection="list" item="item" index="index" separator="," >  
        (#{item.id},#{item.name},#{item.sex},#{item.tel},#{item.address})  
    </foreach>  
</insert> 

其實掌握了 批量插入和批量刪除,批量更新也是一樣的。




 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM