SpringMVC頁面向Controller提交陣列+Mybatis傳多個引數+MySQL一次寫入多條記錄
阿新 • • 發佈:2019-01-03
DAO層定義:
Service層
控制層,authId接收頁面僅提交一個的資料,authId[]接收頁面提交多個authID的資料。required=false,如果頁面一個authId也沒提交,兩個引數都是null。
頁面html
int insertRole2Authorities(@Param("roleId")int roleId, @Param("authorities")List<Integer> authId);
XML檔案:
<!-- 一個角色對應多個許可權,批量insert --> <insert id="insertRole2Authorities" useGeneratedKeys="true" > insert into tm05_roles_authorities (role_id,authority_id) values <foreach collection="authorities" item="authId" index="index" separator="," > (#{roleId,jdbcType=INTEGER},#{authId}) </foreach> </insert>
Service層
@Transactional
public int writeRoleAuth(int roleId, List<Integer> authId) {
int updates = 0;
updates += roleDao.deleteAllAuthByRoleId(roleId);
updates += roleDao.insertRole2Authorities(roleId,authId);
return updates;
}
控制層,authId接收頁面僅提交一個的資料,authId[]接收頁面提交多個authID的資料。required=false,如果頁面一個authId也沒提交,兩個引數都是null。
@ResponseBody @RequestMapping(value={"/edit_auth"}, method=RequestMethod.POST) public Map<String, Object> editRoleAuthorites( @RequestParam(value="roleId", required=true)int roleId, @RequestParam(value="authId", required=false)Integer authId, @RequestParam(value="authId[]", required=false)List<Integer> authorities) { Map<String, Object> modal = new HashMap<String, Object>(3); try{ int ok = 0; if(authId == null && authorities!=null && authorities.size()>0) ok = service.writeRoleAuth(roleId,authorities); else if(authId != null && authorities==null){ authorities = new ArrayList<Integer>(); authorities.add(authId); ok = service.writeRoleAuth(roleId,authorities); } else ok = dao.deleteAllAuthByRoleId(roleId); modal.put("ok", ok); } catch(Exception e){ modal.put("ok", 0); modal.put("error",e.getMessage()); e.printStackTrace(); } return modal; }
頁面html
div class="input-group"> <span class="input-group-addon"> <input type="checkbox" value="1" name="authId"></span> <label class="form-control">許可權1 -- 具體內容</label> </div> <div class="input-group"> <span class="input-group-addon"> <input type="checkbox" value="2" name="authId"></span> <label class="form-control">許可權1 -- 具體內容</label> </div> <div class="input-group"> <span class="input-group-addon"> <input type="checkbox" value="3" name="authId"></span> <label class="form-control">許可權1 -- 具體內容</label> </di<span style="font-family: Arial, Helvetica, sans-serif;">v></span>