springMVC receives array parameters, mybatis receives array parameters, mybatis batch insert / batch delete case

springMVC receives array parameters, mybatis receives array parameters, mybatis batch insert / batch delete case
case is to grant multiple permissions to a user, multiple permissions use their corresponding primary key id as a parameter, form an id array, pass it to springMVC, and then springMVC is passed to mybatis, and then mybatis is inserted in batches. In fact, there are similar scenarios in which multiple batches are deleted, which is also similar.

1. Front page
        <thead><tr><th>Permission selection</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}"/>





    var priv_ids =[];//Define an array   
    $('input[name="priv_id"]:checked').each(function(){ // Traverse each check box whose name is priv_id, the selected one executes function   
        priv_ids.push($.trim($(this).val())); // add the selected value to the array 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');

Submitted data in json format: var indata = {userId:user_id, privIds:priv_ids};
where priv_ids is a An array of ids.

3.
@RequestMapping(value="/setPrivilege")
@ResponseBody
public void setPrivilege(@RequestParam(value = "privIds[]") Integer[] privIds, Integer userId, PrintWriter writer){
    System.out.println(JSON.toJSONString(privIds));
    System.out.println(JSON.toJSONString(userId));
    int result = this.privilegeService.setPrivilegeForUser(privIds, userId);
    System.out.println("result=" + JSON.toJSONString(result));
    Map<String, String> map = new HashMap<>();
    if(result > 0){
        map.put("result", "ok");
        map.put("msg", "设置成功");
        writer.write(JSON.toJSONString(map));We see the use of: @RequestParam(value = "privIds[]" ) Integer[] privIds to get the array parameters from the foreground.}
    }



When springMVC receives parameters, it is best not to use primitive types such as int, long, etc., but to use their corresponding packaging types, otherwise an error will be reported when the incoming parameter is empty, and the packaging type can use null to represent the incoming null value .

4. The processing of the service layer is very simple. Use map to pass parameters to mybatis directly:
@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. Finally, see how the sql in mybatis xml is written:
<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>

We see that foreach is used to loop the passed in array privIds, and the final sql statement is as follows:
insert into user_privilege(user_id, privilege_id) values ​​(3, 1),(3,2),(3,3), (3,4)
user_id is unchanged, and privilege_id is the id value looped out in the array privIds. In fact, it is a batch insertion of the database.
6.


<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>

Comparing batch deletion and batch insertion, it can be seen that open="(" and close=")" in foreach are only at the beginning and end of the loop. Plus, and separator="," is to add a comma every time it is looped.

7. Example of batch inserting incoming object List:
<insert id="batchInsertStudent" parameterType="java.util.List"> 
    insert into student (id,name,sex,tel,address) values
    ​​<foreach collection="list" item="item" index="index" 




In fact, you have mastered batch insertion and batch deletion, and batch update is the same.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326385292&siteId=291194637