天天看點

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

繼續閱讀