一、前言
这边使用mybats的foreach collection的xml集合配置标签属性,实现批量插入INSERT INTO 和 IN 包含逻辑查询SELECT示例,具体参考示例配置说明。
二、示例配置
1. mybatis的xml配置文件
<?xml version="1.0" encoding="UTF-8" ?> @b@<!DOCTYPE mapper @b@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" @b@ "http://mybatis.org/dtd/mybatis-3-mapper.dtd">@b@<mapper namespace="com.xwood.portal.dao.NewsInfoDAO"> @b@ @b@ <!-- 批量新增 -->@b@ <insert id="batchInsert" parameterType="com.xwood.portal.dto.NewsInfoDTO">@b@ INSERT INTO NEWSINFO@b@ (ID,@b@ FOLDER_ID,@b@ FOLDER_DIR,@b@ TITLE,@b@ CON_BODY, @b@ CREATED_BY,@b@ CREATED_DATE,@b@ UPDATED_BY,@b@ UPDATED_DATE,@b@ DATA_STATUS)@b@ <foreach collection="batchInserts" separator="union all"@b@ item="newinfo" index="index" >@b@ select@b@ sys_guid(),@b@ #{newinfo.folderId,jdbcType=VARCHAR},@b@ #{newinfo.folderDir,jdbcType=VARCHAR},@b@ #{newinfo.title,jdbcType=VARCHAR},@b@ #{newinfo.conBody,jdbcType=VARCHAR}, @b@ 'sys',@b@ systimestamp,@b@ 'sys',@b@ systimestamp,@b@ '1'@b@ from dual@b@ </foreach>@b@ </insert>@b@ @b@ @b@ <select id="getList" resultType="com.xwood.portal.dto.NewsInfoDTO" parameterType="com.xwood.portal.dto.NewsInfoDTO">@b@ SELECT @b@ FOLDER_ID folderId,@b@ FOLDER_DIR folderDir, @b@ COUNT(1) gtotal@b@ FROM NEWSINFO ts where DATA_STATUS = '1' @b@ <if test="folderIds != null and folderIds.size>0">@b@ and folder_id in@b@ <foreach collection="folderIds" open="(" close=")" separator="," item="newinfo">@b@ #{newinfo.folderId}@b@ </foreach>@b@ </if> @b@ group by FOLDER_ID,FOLDER_DIR @b@ </select>@b@ @b@ @b@ @b@</mapper>
2. NewsInfoDTO类
public class NewsInfoDTO {@b@ @b@ private String id;@b@@b@ private String folderId;@b@@b@ private String folderDir;@b@@b@ private String title;@b@@b@ private String conBody;@b@ @b@ private Integer gtotal;@b@@b@ private List<NewsInfoDTO > folderIds;@b@@b@ private List<NewsInfoDTO> batchInserts;@b@@b@ public String getId() {@b@ return id;@b@ }@b@@b@ public void setId(String id) {@b@ this.id = id;@b@ }@b@@b@ public String getFolderId() {@b@ return folderId;@b@ }@b@@b@ public void setFolderId(String folderId) {@b@ this.folderId = folderId;@b@ }@b@@b@ public String getFolderDir() {@b@ return folderDir;@b@ }@b@@b@ public void setFolderDir(String folderDir) {@b@ this.folderDir = folderDir;@b@ }@b@@b@ public String getTitle() {@b@ return title;@b@ }@b@@b@ public void setTitle(String title) {@b@ this.title = title;@b@ }@b@@b@ public String getConBody() {@b@ return conBody;@b@ }@b@@b@ public void setConBody(String conBody) {@b@ this.conBody = conBody;@b@ }@b@@b@ public List<NewsInfoDTO> getFolderIds() {@b@ return folderIds;@b@ }@b@@b@ public void setFolderIds(List<NewsInfoDTO> folderIds) {@b@ this.folderIds = folderIds;@b@ }@b@@b@ public List<NewsInfoDTO> getBatchInserts() {@b@ return batchInserts;@b@ }@b@@b@ public void setBatchInserts(List<NewsInfoDTO> batchInserts) {@b@ this.batchInserts = batchInserts;@b@ }@b@@b@ public Integer getGtotal() {@b@ return gtotal;@b@ }@b@@b@ public void setGtotal(Integer gtotal) {@b@ this.gtotal = gtotal;@b@ }@b@@b@}