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 (?,?,?)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章