天天看点

MyBatis 批量插入数据

Map类型参数批量插入

xml文件中sql定义如下:

<!--入参map结构-->
    <!--key:valueList,value:字段值集合 -->
    <!--key:languageKey,value:语言key-->
    <insert id="addTrainRecordBatch" parameterType="java.util.Map">
        insert into test_${languageKey}(code,name)
        values
        <foreach collection="valueList" item="item" index="index" separator=",">
            (#{item.codeValue},#{item.nameValue})
        </foreach>
    </insert>      

具体参数结构如下:

MyBatis 批量插入数据
其实,这里的参数map可以更复杂一些,但一定要包含上面图中的languagKey、valueList这两个键值。

对应的mapper接口中调用函数:

/**
     * 批量插入
     *
     * @param map
     * @return
    public int addTrainRecordBatch(Map map);      

实体类类型参数批量插入

xml文件中sql定义如下:

<insert id="addTrainRecordBatch" parameterType="parameterEntity">
        INSERT INTO test(code,name)
        values
    <foreach collection="list" item="item" index="index" separator=",">
            (#{item.code},#{item.name})
    </foreach>
</insert>      

parameterEntity是数据库表对应的实体类:

@Table(name = "test")
public class Test
    private String code;

    private String name;

    /**
     * @return
    public String getCode() {
        return code;
    }

    /**
     * @param
    public void setCode(String code) {
        this.code = code == null ? null : code.trim();
    }

    /**
     * @return
    public String getName() {
        return name;
    }

    /**
     * @param
    public void setName(String name) {
        this.name = name == null ? null      
/**
     * 批量插入
     *
     * @param trainRecordList
     * @return
    public int addTrainRecordBatch(List<parameterEntity> trainRecordList);      

继续阅读