MyBatis xml foreach循環語句


MyBatis很好的支持批量插入,使用foreach即可滿足

首先創建DAO方法:

package com.youkeda.comment.dao; import com.youkeda.comment.dataobject.UserDO; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.time.LocalDateTime; import java.util.List; //fhadmin.cn @Mapper public interface UserDAO { int batchAdd(@Param("list") List<UserDO> userDOs); } 
<insert id="batchAdd" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id"> INSERT INTO user (user_name, pwd, nick_name,avatar,gmt_created,gmt_modified) VALUES <foreach collection="list" item="it" index="index" separator =","> (#{it.userName}, #{it.pwd}, #{it.nickName}, #{it.avatar},now(),now()) </foreach > </insert> 

foreach相當於執行力java的for循環,他的屬性:

collection指定集合的上下文參數名稱比如這里的@Param("list")
item指定遍歷的每一個數據的變量,一般叫it,可以使用it.userName來獲取具體的值
index集合的索引值,從0開始
separator遍歷每條記錄並添加分隔符
除了批量插入,使用SQL in查詢多個用戶時也會使用:

package com.youkeda.comment.dao; import com.youkeda.comment.dataobject.UserDO; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.time.LocalDateTime; import java.util.List; //fhadmin.cn @Mapper public interface UserDAO { List<UserDO> findByIds(@Param("ids") List<Long> ids); } 
<select id="findByIds" resultMap="userResultMap"> select * from user <where> id in <foreach item="item" index="index" collection="ids" open="(" separator="," close=")"> #{item} </foreach> </where> </select> 
  • open

表示的是節點開始時自定義的分隔符

  • close

表示是節點結束時自定義的分隔符

執行后會變成:

select * from user where id in (?,?,?)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM