Mybatis技术一批量插入、更新、删除、查询

mybatis批量操作:传入参数为list、数组、map写法

  1.foreach简单介绍:

  foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。

说明:

  (1)item表示集合中每一个元素进行迭代时的别名;

  (2)index指定一个名字,用于表示在迭代过程中,每次迭代到的位置;

  (3)open表示该语句以什么开始;

  (4)separator表示在每次进行迭代之间以什么符号作为分隔符;

  (5)close表示以什么结束。

 详细解释:

  foreach属性

属性描述
item 循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。
具体说明:在list和数组中是其中的对象,在map中是value。
该参数为必选。
collection 要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象用map代替作为键。
当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array,map将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:
如果User有属性List ids。入参是User对象,那么这个collection = "ids"
如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"
上面只是举例,具体collection等于什么,就看你想对那个元素做循环。
该参数为必选。
separator 元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
open foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选。
close foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
index 在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。

collection属性是在使用foreach的时候最关键的也是最容易出错的,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况: 

  (1)如果传入的是单参数且参数类型是一个List的时候,collection属性值为list .

  (2)如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array .

  (3)如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key.

一、集合list方式:

  1、批量插入:insert

  (1)mapper.java中(Construction为实体类)

public interface ConstructionMapper {
    public int insert(List<Construction> record);
}

  (2)mapper.xml中:

  <insert id="insert" useGeneratedKeys="true" parameterType="java.util.List">
    insert into tmp_research_construction (juid,juid2,construction,createTime,updateTime,createUserJuid) values
    <foreach collection="list" item="data" separator="," index = "index">
      (#{data.juid},#{data.juid2}, #{data.construction},NOW(),NOW(),#{data.createuserjuid})
    </foreach>
  </insert>

2、批量删除:delete

  (1)mapper.java中(实体类)

public interface DirectionMapper {
    public int del(Map<String, Object> map);
}

  (2)mapper.xml中:

  <delete id="del" parameterType="Map" >
    delete from research_baseinfo_direction where uuid in
    <foreach collection="uuid" item="id" index="index" open="(" close=")" separator=",">  
       #{id}  
    </foreach>
  </delete>

  实现类中如何入参?参数必须是数组比如:integer[],或者List<Integer>,然后放入map中,即可。
3、批量更新:update

  (1)mapper.java中(实体类)

public interface DirectionMapper {
    public int submitData(Map<String, Object> map);
}

  (2)mapper.xml中:

  <!-- 批量提交审核 -->
  <update id="submitData" parameterType="Map" >
    update research_baseinfo_direction checkState = #{checkState},updateTime = NOW(),updateUserJuid = #{updateUserJuid} where uuid in
    <foreach collection="uuid" item="id" index="index" open="(" close=")" separator=",">  
       #{id}
    /foreach>
  </update>

  参数是数组比如:integer[],或者List<Integer>,然后放入map中,即可。

4.批量查询:select

  (1)mapper.java中(实体类)

public interface DirectionMapper {
    public int getLists(List<Employees> list);
}

  (2)mapper.xml中:

<!--List:forech中的collection属性类型是List,collection的值必须是:list,item的值可以随意,Dao接口中参数名字随意 -->  

<select id="getLists" resultType="Employees">  

   select * from EMPLOYEES e where e.EMPLOYEE_ID in  

   <foreach collection="list" item="employeeId" index="index" open="(" close=")" separator=",">  

       #{employeeId}  

   </foreach> 

</select>


  这里没有在select参数那类型,没有将数组放入map中插入,这里传入的参数类型直接用:list即可。

二、数组:Array,其他类似,这里只以查询为主,其他的可以参照上面的方式。

  (1)mapper.java中(实体类)

public interface DirectionMapper {
    public List<Employees> getArrays(String[] employeeId);  
}

  (2)mapper.xml中:

<!--Array:forech中的collection属性类型是array,collection的值必须是:list,item的值可以随意,Dao接口中参数名字随意 -->  
<select id="getArrays" resultType="Employees">  
select * from EMPLOYEES e where e.EMPLOYEE_ID in 
<foreach collection="array" item="employeeId" index="index" open="(" close=")" separator=",">  
#{employeeId} 
</foreach>  
</select> 

三、map已经在一中,使用过,可以参考一中,实现方式。

补充:

  (1)sql:

insert into deliver(id,name) select ?,? from dual union all select ?,? from dual

  (2).mppper.xml中实现方式:

<resultMap id="BaseResultMap" type="com.jitri.vo.deliver" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
    id, name
</sql>

<insert id="addList">
   INSERT INTO DELIVER ( <include refid="Base_Column_List" /> )
   <foreach collection="deliverList" item="data" separator="UNION ALL">  
       SELECT  #{data.id},#{data.name} FROM DUAL  
   </foreach>  
</insert> 

方式二:

  1、(1)xml:

<insert id="insertCollect" parameterType="java.util.Map">  
    insert into students (id,name) 
<foreach collection="finProductIds" item="item" separator="union all" > select #{finConsultId} as col1, #{item} as col2 from dual </foreach> </insert>

  java中:

String[] insertIdsArray = insertIds.split(",");  
List<Long> finProductIds = new ArrayList<Long>();  
for(int i=0; i<insertIdsArray.length; i++){  
    finProductIds.add(Long.parseLong(insertIdsArray[i]));  
}  
  
Map<String,Object> map = new HashMap<String,Object>();  
map.put("finConsultId", finConsultId);  
map.put("finProductIds", finProductIds);  
dao.insertCollect(map); 

  2、(1)sql:

select count(*) from key_cols where col_a = ? AND col_b = ?

  (2)mapper.xml中:

<select id="sel_key_cols" resultType="int">    
    select count(*) from key_cols where    
    <foreach item="item" index="key" collection="map" open="" separator="AND" close="">
${key} = #{item}
</foreach> </select>

  说明:一定要注意到$和#的区别,$的参数直接输出,#的参数会被替换为?,然后传入参数值执行

三。批量更新特殊情况

  1.sql:

update research_project_vertical set receivedFee=(receivedFee+11) where juid='aa' and projectCode='bb';
update research_project_vertical set receivedFee=(receivedFee+11) where juid='dd' and projectCode='cc';
---------------

  2.xml中实现方式:

<!-- 批量更新到账信息 -->
<update id="importUpdateReceivedFee" parameterType="java.util.List">
    <foreach collection="list" item="data" index="index" separator=";">
       update research_project_vertical set receivedFee=(receivedFee+#{data.receivefee}) 
where juid=#{data.juid} and projectCode=#{data.projectcode}
</foreach>
</update>

  3、java中实现方式:

//批量更新到账信息
public int importUpdateReceivedFee(List<FeeFromVerticalAndHorizontal> list);

批量删除:
  1、xml中:

<delete id="del" parameterType="Map" >
    delete from year_direction where juid = #{juid} and juid2=#{juid2} <if test="yearType!=null and yearType!=''"> and yearType=#{yearType}</if>;
    delete from year_vi where juid = #{juid} and juid2=#{juid2} <if test="yearType!=null and yearType!=''"> and yearType=#{yearType}</if>;
</delete>

2.java中:
    /**批量删除**/
    public int del(Map<String,Object> map);

posted @ 2018-01-28 22:27  小码农成长记  阅读(1012)  评论(0)    收藏  举报