Mybatis DAO层参数传递的几种方式(普通参数、List、Map、混合)

本文详细介绍了MyBatis中不同类型的参数传递方式,包括普通参数、单个和多个集合类型参数、列表参数及Map参数的使用。通过示例展示了Dao层和Mapper.xml的配置,阐述了如何在SQL语句中灵活处理各种参数,实现数据的增删改查操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 普通参数传参(@Param)

Dao层:

    int deleteById(@Param(”id”)Integer id, @Param (”name”) String name)) ;

Mapper.xml:

    <delete id="deleteById">
          DELETE FROM students
             WHERE id = #{id,jdbcType=INTEGER}
             <if test="name != null" >
                 ,p_name = #{name}
            </if>  
    </delete> 

2. 单个(多个)集合类型参数

Dao层:

	int batchUpdateStatusOfChecking(@Param(value=”ids”)String[] ids);

Mapper.xml:

    <update id="batchUpdateStatusOfChecking">
        update students
        <set>
            status = 5
        </set>
        <if test="ids != null and ids != ''">
            where status in(2,4)
            and id in
            <foreach collection="ids" item="item" index="index" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
    </update>

解析:collection表示传入的数组参数的名字,item集合中每一个元素进行迭代时的别名。

3. 列表(List)

Dao层:

	int batchInsertStudent(List<String> students);

Mapper.xml:

   <insert id="batchInsertStudent" parameterType="java.util.List">
        insert into student (id,name,sex,tel,address) values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.id},#{item.name},#{item.sex},#{item.tel},#
            {item.address})
        </foreach>
    </insert>

4. Map

Dao层:

	int batchUpdateStatusForChecking(@Param("map") Map<String,String> map, @Param("updateBy")String updateBy);

Mapper.xml:

    <update id="batchUpdateStatusForChecking">
        <foreach collection="map" index="key"  item="ent" separator=";">
            update search
            set status = 2
            <if test="updateBy!= null">
                ,update_by = #{updateBy}
            </if>
            ,update_time = #{ent}
            where id = #{key}
            and status = 1
        </foreach>
    </update>

6. 混合参数(既有简单类型,同时又有集合类型)

Dao层:

	int batchUpdateStatusOfChecking(@Param("ids")String[] ids,@Param("lastUpdateBy")String lastUpdateBy);

Mapper.xml:

    <update id="batchUpdateStatusOfChecking">
        update search
        <set>
            status = 5
            <if test="lastUpdateBy != null" >
                ,last_update_by = #{lastUpdateBy}
            </if>
        </set>
        <if test="ids != null &amp;&amp; ids != ''">
            where status in(2,4)
            and id in
            <foreach collection="ids" item="item" index="index" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
    </update>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值