Mybaist 注解 foreach 嵌套循环实现批量插入

第一种写法(#使用占位符推荐):

@Insert("<script>"
				+ " insert into ${tb}  "
				+" <foreach collection=\"fields\" item=\"field\"   separator = \",\" open='(' close=')'> "
				+ "`${field}`"
				+"</foreach>"
				+ "values"
				+" <foreach collection=\"list\" item='mvo' index=\"list_index\"  separator = \",\" > "
				+"   <foreach collection=\"mvo.keys\" item=\"key\" open='(' close=')' separator = \",\">"
				+"    #{mvo.${key}} " 
				+"   </foreach>  "
				+"</foreach>"
				+ "</script>")
		int insertBatch(@Param("list")List<Map<String,Object>> housingList,@Param("fields") Set<String> keys,@Param("tb") String table) throws Exception;

  执行结果:

    insert into

    dmp_department_work ( `functional` , `num` , `power` , `state` , `department` , `table` )

    values ( ? , ? , ? , ? , ? , ? ) ,( ? , ? , ? , ? , ? , ? ) 

  

 第二种写法($不使用占位符):

 

@Insert("<script>"
				+ " insert into ${tb}  "
				+" <foreach collection=\"fields\" item=\"field\"   separator = \",\" open='(' close=')'> "
				+ "  `${field}`"
				+" </foreach>"
				+ "values"
				+" <foreach collection=\"list\" item='mvo' index=\"list_index\"  separator = \",\" > "
				+"   <foreach collection=\"mvo.keys\" item=\"key\" open='(' close=')' separator = \",\">"
				+"    '${mvo[key]}' " 
				+"  </foreach>  "
				+"</foreach>"
				+ "</script>")
		int insertBatch(@Param("list")List<Map<String,Object>> housingList,@Param("fields") Set<String> keys,@Param("tb") String table) throws Exception;

  执行结果:

    insert into

    dmp_department_work ( `functional` , `num` , `power` , `state` , `department` , `table` )

    values ( '17' , '1' , '152' , '0' , '1' , 'dmp_data_task' ) , ( '17' , '1' , '153' , '0' , '1' , 'dmp_data_meet' ) 

 

注意:

   使用注解实现:

  •  ${}表示直接注入值,  使用#{}符号表示占位取值
  •  map遍历取值三种方式:item.[key] 或 item[key] 或  item.key,如果传入的是java实体,使用item.key取值

posted on 2019-08-15 15:21  滚动的蛋  阅读(2052)  评论(0编辑  收藏  举报

导航