MyBatis foreach语句批量插入数据

来源:互联网 发布:域名没备案能解析吗 编辑:程序博客网 时间:2024/05/22 10:42

本例技术:Spring+SpringMVC+MyBatis+Oracle


问题描述:需要将程序里的一个集合保存到数据库里,集合的类型对应数据库的一个实体,若在程序里遍历集合再一条条保存到数据库表中有点麻烦,这里可以利用MyBatis 的 foreach语句实现批量插入数据。


核心代码清单:

Item(实体类):

public class Item {    private String itemCode;//项目代码    private String itemName;//项目名称    private String itemValue;//项目值(多个值用逗号隔开)    private String itemCategory;//项目所属类别    public String getItemCode() {        return itemCode;    }    public void setItemCode(String itemCode) {        this.itemCode = itemCode;    }    public String getItemName() {        return itemName;    }    public void setItemName(String itemName) {        this.itemName = itemName;    }    public String getItemValue() {        return itemValue;    }    public void setItemValue(String itemValue) {        this.itemValue = itemValue;    }    public String getItemCategory() {        return itemCategory;    }    public void setItemCategory(String itemCategory) {        this.itemCategory = itemCategory;    }}

Service实现层方法:

    public Integer submitItem(List<Item> list ){        return researchMapper.submitItem(list);    }

MyBatis的mapper配置文件的语句(在Oracle数据中,多条数据之间用union all 连接,MySQL数据库用,):

 <insert id="submitItem"  parameterType="java.util.List">        insert into ITEM (        ITEM_CODE,        ITEM_NAME,        ITEM_VALUE,        ITEM_CATAGORY        )        select  item.* from        (        <foreach collection="list" item="item" index="index" separator="UNION ALL" >            select            #{item.itemCode,jdbcType=VARCHAR},            #{item.itemName,jdbcType=VARCHAR},            #{item.itemValue,jdbcType=VARCHAR},            #{item.itemCategory,jdbcType=VARCHAR}            from dual        </foreach>        ) item    </insert>

<!--MySql写法--><insert id="submitItem"  parameterType="java.util.List">    insert into ITEM (    ITEM_CODE,    ITEM_NAME,    ITEM_VALUE,    ITEM_CATAGORY    )    values    <foreach collection="list" item="item" index="index" separator="," >      (        #{item.itemCode,jdbcType=VARCHAR},        #{item.itemName,jdbcType=VARCHAR},        #{item.itemValue,jdbcType=VARCHAR},        #{item.itemCategory,jdbcType=VARCHAR}     )    </foreach></insert>

foreach元素解析:

foreach元素是一个遍历集合的循环语句,它支持遍历数组,List和Set接口的集合。

foreach元素中,collection是传进来的参数名称,可以是一个数组或者List、Set等集合;

                             item是循环中当前的元素(配置的item的名字随意取,类似于iterator);

                             index是当前元素在集合中的位置下标;

                             seperator是各个元素的间隔符;

                             ()分别是open和close元素,表示用什么符号将这些集合元素包装起来。 


注意:由于一些数据库的SQL对执行的SQL长度有限制,所以使用foreach元素的时候需要预估collection对象的长度;foreach除了用于本示例的循环插入,亦可用于构建in条件中(可自行尝试)。