mybatis 批量增删改查的几种情况

由于项目中频繁的使用批量操作,所以拿出来总结一下,供以后复习参考~
批量操作,基本是利用List(或array)或者Map封装好参数后,作为parameterType,然后使用foreach来操作集合,从而达到想要的效果。
1. 参数是Map

  • 批量插入
    用例:

    < insert id=”save” parameterType=”java.util.Map”>
    insert into TB_A(
    id,type,point
    )values
    < foreach item=”item” index=”index” collection=”paralist” separator=”,” >
    (
    #{item.id},#{type},#{item.point}
    )
    < / foreach>
    < /insert>

    其中,paralist可以是封装在参数Map中List< Map< String,Object>>类型,也可以是一个array或者List< String>类型,根据具体需求选择使用哪种方式。如果批量插入的操作每次都具有多个参数,如上例中的id和point,可以选择List< Map< String,Object>>来实现,而type可以放在外层的Map中。如果每次循环只有一个变量,其他的参数都是相同的值,则可以选择一个array或者List< String>类型,将变量参数封装在里面即可。

  • 批量删除

< delete id=”deleteAll” parameterType=”java.util.Map”>
delete from TB_A where
type =#{type} and
id in
< foreach item=”item” index=”index” collection=”paralist” open=”(” close=”)” separator=”,”>
#{item.id}
< /foreach>
< /delete>

使用场景与批量插入类似,如果paralist中只有id一个属性值,则foreach内可以直接写为#{item}。

  • 批量更新

< update id=”update” parameterType=”java.util.Map”>
< foreach collection=”paralist” item=”item” index=”index” separator=”;” >
update TB_A
< set>
point=#{item.point}
< /set>
where
id= #{item.id}
and type=#{item.type},
< /foreach>
< /update>

使用场景与例1类似,point,id封装与paralist中,而paralist与type封装于Map中。

  • 批量查询

< select id=”getdata” parameterType=”java.util.Map” resultType=”data”>
< foreach item=”item” index=”index” collection=”paralist” separator=”;”>
select id,type,point
from TB_A
where id = #{item.id}
< /foreach>
< /select>

上面这种方法使用时注意,如果paralist中的第一个元素在数据库中为空,则最终所有的结果都会为空。可以用下边这种方式避免这种状况:

< select id=”getdata” parameterType=”java.util.Map” resultType=”data”>
select id,type,point
from TB_A
where id in
< foreach item=”item” index=”index” collection=”paralist” open=”(” close=”)” separator=”,”>
#{item.id}
< /foreach>
< /select>

注意返回类型,根据自己的需求选,可以是一个entity,可以是Map。
2. 参数是List

参数是List类型与Map类型相似,List内部可以是Map,可以是String,还可以是一个entity类等,根据需求选择。
下例List中使用了Map类型:如果是用数组类型,则collection改为array

< insert id=”addShops” parameterType=”java.util.List”>
insert into TB_A(
id,point,type
) values
< foreach item=”item” index=”index” collection=”list” separator=”,” >
(
#{item.id},#{item.point}, #{item.type}
)
< /foreach>
< /insert>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值