zoukankan      html  css  js  c++  java
  • mybatis 学习笔记(4) —— 批量新增数据

    1、业务是从前台传入List<T> ,在controller层接受参数,并进行批量新增操作。

    2、需要处理的细节

      a) mybatis可以支持批量新增,注意数据表需要将主键设置成自增列。

          b) 由于spring mvc 无法将参数[{id:0,text:'a'},{id:1,text:'b'}] json字符串转换为对应的List<T>,因此需要自己手动封装一个方法用于将传入的字符串转换为泛型集合

    3、具体实现步骤

      a) js提交

      需要注意的是必须在参数名上加引号

                            var deptPersonList = $('#personList').datagrid('getSelections');
                            if(deptPersonList.length > 0 ){
                                var jsonstr = "[";
                                $.each(deptPersonList,function(index,item){
                                    jsonstr += "{"departmentId":""+selectedId+"","personId":""+item.personId+""},";
                                });
                                jsonstr = jsonstr.substr(0,jsonstr.length-1);    
                                jsonstr += "]";
                                
                                $.post('setDeptPerson.action', { params: jsonstr }, function (data) {
                                    if (data == true) {
                                        $.messager.alert("提示", "保存成功!");
                                        $("#setDialog").dialog('destroy');
                                        $('#departmentList').datagrid('reload');
                                    } else {
                                        $.messager.alert("提示", "保存失败!");
                                    }
                                });
                            }else{
                                $.messager.alert("提示","请至少选择一条数据进行保存!");
                            }

      b) controller

      getParameterString为我自定义的封装客户端提交请求数据的公共方法,对HttpServletRequest和HttpServletResponse进行封装

        /**
         * 设置部门下人员
         * @param departperson
         * @return
         * @throws Exception 
         */
        @SuppressWarnings("unchecked")
        @RequestMapping(value="/setDeptPerson",method=RequestMethod.POST)
        @ResponseBody
        public Boolean setDeptPerson() throws Exception{
            String json = getParameterString("params");
            List<DepartPerson> departpersonList = formatJsonUtil.readJson(json, List.class, DepartPerson.class);
             return departmentService.add(departpersonList);
        }  

      c) 参数处理类

    package com.frame.core.util;
    
    import com.fasterxml.jackson.databind.JavaType;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class formatJsonUtil {
    
        public static <T> T readJson(String jsonStr,Class<T> collectionClass,Class<?>... elementClass) throws Exception{
            ObjectMapper mapper = new ObjectMapper();
            JavaType javatype = mapper.getTypeFactory().constructParametricType(collectionClass, elementClass);
            return mapper.readValue(jsonStr, javatype);
        }
    }

      d) mapper.xml配置

        直接上mapper的配置方法,add方法就是mybatis的sqlSession的insert方法的封装

        <!-- 批量插入部门人员对应关系表 -->
        <insert id="insertDeptPersons" useGeneratedKeys="true" parameterType="java.util.List">
            <selectKey resultType="int" order="AFTER">
                SELECT 
                LAST_INSERT_ID()
            </selectKey>
            INSERT INTO departmentPerson (personId,departmentId)
            VALUES
            <foreach collection="list" item="item" index="index" separator=",">
                (#{item.personId},#{item.departmentId})
            </foreach>
        </insert>    

      非常简单,也非常直观。对于事务的处理在后面的博文中有具体说明。

  • 相关阅读:
    crossvcl使用
    CSS垂直居中的方法
    IIS7 启用GZip压缩
    javascript arguments解释,实现可变长参数。
    DataTable转List<dynamic>
    Bootstrap表单
    Func<T>、Action<T> 的区别于说明
    jQuery.fn.extend() 与 jQuery.extend()
    javascript this关键字指向详解
    javascript call与apply关键字的作用
  • 原文地址:https://www.cnblogs.com/cklovefan/p/5559394.html
Copyright © 2011-2022 走看看