6.mybatis之foreach的批量操作

之前已经用标签处理了List 集合数据,foreach 标签还有强大的功能,用于批量的 增、删、改 操作
1.批量添加

public void insertEmployeeBatch(@Param("emps")List<Employee> emps )
<insert id="insertEmployeeBatch">
	 	 insert into tbl_employee(last_name, gender, descr ) values
	 	 <foreach collection="emps" item="currEmp" separator=",">
	 	 	(#{currEmp.lastName},#{currEmp.gender},#{currEmp.descr})
	 	 </foreach>
	 </insert>

2.批量修改, 原生的jdbc不支持多条sql语句的拼接执行,要添加一个配置 allowMultiQueries=true,例
jdbc.url=jdbc:mysql://localhost:3306/data?allowMultiQueries=true

<update id="insertEmployeeBatch">
	 	<foreach collection="emps" item="currEmp" >
	 	 update  tbl_employee  set  
	 	 last_name = #{currEmp.lastName} , gender = #{currEmp.gender}, descr = #{currEmp.descr} 
	 	 where id = #{currEmp.id};
	 	 </foreach>
</update>

3.批量删除

public List<TAdmin> selectByIds(@Param("ids") List ids);
<delete id="selectByIds" resultType="com.mybatis.bean. Admin">
        delete  from admin  where id in
        <foreach collection="ids" item="currentId" open="(" close=")" separator=",">
            #{currentId}
        </foreach>
    </delete>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Tk.mybatis的`@UpdateProvider`注解来实现批量更新。 首先,创建一个Mapper接口,使用`@UpdateProvider`注解来指定更新操作的提供者类和方法。在提供者类中编写批量更新的SQL语句。 ```java @Mapper public interface MyMapper { @UpdateProvider(type = MyBatchUpdateProvider.class, method = "dynamicSQL") void batchUpdate(List<MyEntity> entityList); } ``` 然后,创建一个提供者类,并实现相应的方法来生成动态SQL语句。 ```java public class MyBatchUpdateProvider { public String batchUpdate(Map<String, Object> map) { List<MyEntity> entityList = (List<MyEntity>) map.get("list"); StringBuilder sb = new StringBuilder(); sb.append("UPDATE my_table SET "); sb.append("<foreach collection='list' item='entity' separator=','>"); sb.append("column1 = #{entity.column1},"); sb.append("column2 = #{entity.column2}"); sb.append("</foreach>"); sb.append("WHERE id IN "); sb.append("<foreach collection='list' item='entity' open='(' close=')' separator=','>"); sb.append("#{entity.id}"); sb.append("</foreach>"); return sb.toString(); } } ``` 在上述示例中,我们使用了`<foreach>`标签来循环遍历`entityList`,生成批量更新的SQL语句。 最后,你可以在需要进行批量更新操作的地方注入`MyMapper`接口,并调用`batchUpdate`方法即可。 ```java @Autowired private MyMapper myMapper; public void updateBatch(List<MyEntity> entityList) { myMapper.batchUpdate(entityList); } ``` 这样,你就可以使用Tk.mybatis实现批量更新操作了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值