批量插入
void batchInsertWorks(@Param("empNo") String empNo, List<Works> worksList); <insert id="batchInsertWorks" parameterType="java.util.List"> delete from mf_works_schedule where emp_no = #{empNo}; insert into mj_works(id_, emp_no, rest_day, rest_date, update_time) values <foreach collection ="worksList" item="item" index= "index" separator =","> ( #{item.id}, #{item.empNo}, #{item.restDay},#{item.restDate}, now() ) </foreach > ON DUPLICATE KEY UPDATE update_time=now(); </insert>
-
这里传递的参数是List,所有parameterType为java.util.List
-
在<insert>或其他mybatis的标签中,可以写多个SQL语句,数据库会依次执行,记得一个语句结束后用分号结尾
-
foreach中collection的内容(worksList),就是传递的参数的名字
-
separator表示用两个对象之间用逗号相隔,即:insert into xxx(column1,column2,column3) values(...), (...), (...)
-
item就有点像:for(Works item : worksList) { ... }
-
index在List和数组中,表示元素的序号,在map中,index表示元素的key
IN查询、删除
List<Order> queryByAppointmentDate(@Param("dateArray") String[] dateArray); <select id="queryByAppointmentDate" resultMap="xxx.xxx.xxx.Order"> select * from mj_order where appointment_date in <foreach collection="dateArray" item="item" index="index" open="(" separator="," close=")"> ( #{item} ) </foreach> </select>
这里的foreach参数和批量插入类似,多了个open和close,分表表示该语句从什么时候开始,什么时候结束
删除也类似:
void deleteEmpRestInfo(@Param("idArray") String[] idArray); <delete id="deleteEmpRestInfo"> delete from mj_works where id_ in <foreach collection="idArray" item="item" index="index" open="(" separator="," close=")"> ( #{item} ) </foreach> </delete>
批量更新参数传入的是map写法
/** * @Author: Wu * @Description: 批量更新 * @Date: */ @Test public void deleteByUpdates(){ Map<String,Object> map =new HashMap<>(); List list=new ArrayList(); list.add(1); list.add(2); map.put("status",2); map.put("list",list); int a= terminalPrivilegesMapper.updateStatus(map); System.out.println(a); <!--批量更新状态--> <update id="updateStatus" parameterType="java.util.Map"> UPDATE INFO_TERMINALPRIVILEGES SET STATUS = #{status} WHERE ID IN <foreach item="item" collection="list" separator="," open="(" close=")"> #{item,jdbcType=DECIMAL} </foreach> </update>
批量更新传入参数为list写法
<!-- 批量逻辑删除信息 --> <update id="logicDeletes" parameterType="list"> UPDATE INFO_TERMINALTYPE SET DELETED = 1 WHERE ID IN <foreach item="item" collection="list" separator="," open="(" close=")"> #{item,jdbcType=DECIMAL} </foreach> </update>