【mybatis】mapper.xml中foreach的用法,含批量查询、插入、修改、删除方法的使用

博客介绍了xml文件中foreach的主要属性,包括collection、item等。详细阐述了其在数据库操作中的应用,如批量查询、插入、更新和删除数据。插入和更新数据分别介绍了不同的实现方法,还给出了部分对应的Mapper接口代码和SQL映射文件示例。

一、xml文件中foreach的主要属性

foreach元素的属性主要有 collection,item,index,separator,open,close。
collection: 表示集合,数据源
item :表示集合中的每一个元素
index :用于表示在迭代过程中,每次迭代到的位置
separator :表示在迭代时数据以什么符号作为分隔符
open :表示该语句以什么开始
close :表示以什么结束

二、foreach批量查询数据

1、当查询的参数只有一个时

例如:findByIds(List ids)
a.如果参数类型为List,在使用时,collection的属性需指定为list
b.如果参数类型为数组,则在使用时,collection属性需指定为array

<select id="findByIdsMap" resultMap="BaseResultMap">
         Select  sum(mark)
         from table_user where user_id in
                  <foreach item="item" index="index" collection="list" 
                         open="(" separator="," close=")">
                        #{item}
                </foreach>
  </select> 

2、当查询的参数是一个对象时

例如:findByIds(List userList)

<select id="findByIdsMap" resultMap="BaseResultMap">
         Select sum(mark)
         from table_user where user_id in
                  <foreach item="item" index="index" collection="list" 
                         open="(" separator="," close=")">
                        #{item.userId}
                </foreach>
  </select> 

三、foreach批量插入数据

实现foreach批量插入数据有两种方法,一种是只发送一条 SQL,插入的多条数据之间通过”,” 分隔开,另一种方式是每插入一条数据就发送一条 SQL 语句,多个 SQL 语句之间用“;”分割。

1.一条 SQL 批量插入数据

对应的Mapper接口代码如下:

/** 返回值为 Integer 类型 */
Integer addStudentByList(@Param("list") List<Student> list);

对应的SQL 映射文件如下:

<insert id="addStudentByList" parameterType="">
    INSERT INTO Student(username, age, password) VALUES 
    <foreach collection="list" item="item" separator=",">
        (#{ item.username}, #{ item.age}, #{ item.password})
    </foreach>
</insert>
2.执行多条 SQL 批量插入数据

对应的Mapper接口代码和一条 SQL 批量插入数据相同
对应的SQL 映射文件在一条 SQL 批量插入数据的基础上修改如下:

<insert id="addEmpsByList" parameterType="com.jas.mybatis.bean.Employee">
    <!-- 每插入一条数据就执行一次 SQL,中间用";"分隔开  -->
    <foreach collection="list" item="emp" separator=";">
        INSERT INTO Student(username, age, password) VALUES
        (#{ item.username}, #{ item.age}, #{ item.password})
    </foreach>
</insert>

三、foreach批量更新数据

实现foreach批量插入数据有两种种方法,第一种是一条sql语句来批量更新数据,第二种是批量更新的sql。

一条 SQL 批量更新数据

一条sql语句来批量更新所有数据,下面直接看一下在mybatis中通常是怎么写的(去掉mybatis语法就是原生的sql语句了,所有就没单独说sql是怎么写的)
对应的SQL 映射文件如下:

<update id="updateBatch" parameterType="java.util.List">
    update Student set  username=
    <foreach collection="list" item="item" index="index" separator=" " open="case ID" close="end">
        when #{ item.id} then #{ item.username}
    </foreach>
    where id in
    <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
        #{ item.id,jdbcType=BIGINT}
    </foreach>
</update>
<------------------------------------分隔符-------------------------------->
 <update id="updateBatch"  parameterType="java.util.List">  
    <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update Student
        <set>
            username=${ item.username}
        </set>
        where id = ${ item.id}
    </foreach>      
</update>

四、foreach批量删除数据

所对应的SQL映射文件如下:

<delete id="delAssetstype" parameterType="java.util.List">
       DELETE FROM WHERE id in
       <foreach collection="list" item="item" open="(" close=")" separator=",">
           #{ item}
       </foreach>
   </delete>

对应的Mapper接口代码如下:

public void deleteAssetstype(List<Integer> ids);
MyBatis 中,`<insert>` 标签用于定义插入数据的 SQL 语句。它支持多种属性和嵌套标签,允许灵活地处理不同的插入场景,包括获取自增主键、批量插入等。 ### 基本用法 最简单的 `<insert>` 标签用法是直接编写 `INSERT INTO` 语句,并通过 `#{}` 占位符传入参数: ```xml <insert id="insertUser"> INSERT INTO users (username, email) VALUES (#{username}, #{email}) </insert> ``` 其中 `id` 属性对应 Mapper 接口中的方法名,`#{username}` 和 `#{email}` 是从传入对象中提取的属性值。 ### 获取自增 ID 若数据库使用自增主键(如 MySQL 的 `AUTO_INCREMENT`),可以通过设置 `useGeneratedKeys` 和 `keyProperty` 来自动将生成的主键值回填到实体对象中: ```xml <insert id="insertUser" useGeneratedKeys="true" keyProperty="id"> INSERT INTO users (username, email) VALUES (#{username}, #{email}) </insert> ``` 在此配置下,执行插入操作后,MyBatis 会将新记录的自增 ID 设置到传入的对象的 `id` 字段中 [^1]。 ### 批量插入 对于需要一次性插入多条记录的情况,可以使用 `<foreach>` 标签遍历集合或数组,并构造多值插入语句: ```xml <insert id="batchInsertUsers"> INSERT INTO users (username, email) VALUES <foreach collection="list" item="user" separator=","> (#{user.username}, #{user.email}) </foreach> </insert> ``` 此示例中,`collection="list"` 表示传入的是一个 List 集合,`item="user"` 定义了集合中每个元素的别名,`separator=","` 指定每项之间以逗号分隔 [^2]。 ### 使用 `<selectKey>` 获取非自增主键 某些数据库不支持自动生成主键(如 Oracle),此时可以使用 `<selectKey>` 子标签手动指定主键值的获取方式: ```xml <insert id="insertUserWithSequence"> <selectKey keyProperty="id" resultType="long"> SELECT NEXTVAL('user_seq') FROM dual </selectKey> INSERT INTO users (id, username, email) VALUES (#{id}, #{username}, #{email}) </insert> ``` 上述代码先执行 `<selectKey>` 中的语句获取序列值作为主键,再插入数据 [^2]。 ### 示例代码总结 以下是一个完整的 mapper.xml 插入语句示例,包自增主键和批量插入两种情况: ```xml <mapper namespace="com.example.mapper.UserMapper"> <insert id="insertUser" useGeneratedKeys="true" keyProperty="id"> INSERT INTO users (username, email) VALUES (#{username}, #{email}) </insert> <insert id="batchInsertUsers"> INSERT INTO users (username, email) VALUES <foreach collection="list" item="user" separator=","> (#{user.username}, #{user.email}) </foreach> </insert> </mapper> ``` ###
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cc阿正

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值