mybatis从mapper接口传递参数到XML总结

文章标签: 接口传递参数 @Param 批量处理 传递多个参数 批量加事务
(1)接口传递一个变量到xml

接口
selectByPrimaryKey(String id);
对应xml
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
   *
    from table_name
    where ID = #{id,jdbcType=VARCHAR}
  </select>
1
2
3
4
5
6
7
8
9
(2)传递一个对象到xml

接口
int insert(User user);
对应xml
<insert id="insert" parameterType="com.csdn.User" >
    insert into user (ID, NAME, CODE)
    values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{code,jdbcType=VARCHAR})
  </insert>
1
2
3
4
5
6
7
总结:对于这种单个参数的,parameterType一定要与传入的参数类型一直,传递没有问题
(3)传递一个List或者String[]
参数写注解@Param

接口
void deleteByIds(@Param("ids")String[] ids);
对应xml
<delete id="deleteByIds" parameterType="java.lang.String" >
    delete from HJJ_PROBLEM_REPORT
    where ID in 
    <foreach item="id" index="index" collection="ids"   
           open="(" separator="," close=")">  
            #{id}  
     </foreach>
  </delete>
1
2
3
4
5
6
7
8
9
10
11
参数不写注解@Param

void deleteByIds(String[] ids);
对应xml
<delete id="deleteByIds" parameterType="java.lang.String" >
    delete from HJJ_PROBLEM_REPORT
    where ID in 
    <foreach item="id" index="index" collection="array"   
           open="(" separator="," close=")">  
            #{id}  
     </foreach>
  </delete>
1
2
3
4
5
6
7
8
9
10
总结:
1)对于写了注解@Param的参数,parameterType="java.lang.String"可以省略
2)如果没写注解@Param,parameterType不能缺省,并且类型一定要与List或者数组里面的元素类型相同
举例:

void batchInsert(List<User> users);
对应xml
<insert id="batchInsert" parameterType="com.csdn.User" >
    BEGIN  
    <foreach collection="list" item="item" index="index" separator="">  
        insert into user (ID, NAME, CODE)
        values (#{item.id,jdbcType=VARCHAR}, #{item.name,jdbcType=VARCHAR}, #{item.code,jdbcType=VARCHAR})
    </foreach>
    COMMIT;  
    END;  
  </insert>  
1
2
3
4
5
6
7
8
9
10
11
注意:没有写注解@Param,如果传递的是数组,那么需要foreach里面collection必须写array表明传递的参数是数组,然后结合parameterType,mybatis可以分析出数组里面的元素类型;
如果传递的是list,那么需要foreach里面collection必须写array表明传递的参数是list,然后结合parameterType,mybatis可以分析出list里面的元素类型。

(4)如果接口中传递了多种类型的参数,parameterType应该怎么写?

接口
select(String id, int num);
1
2
参数类型有多个,而parameterType只能写一种,怎么处理呢?这时候可以使用@Param注解

select(@Param("id")String id, @Param("num")int num);
对应xml
<select id="selectByPrimaryKey" resultMap="BaseResultMap" >
    select 
   *
    from table_name
    where ID = #{id,jdbcType=VARCHAR}
    and NUM =  #{num,jdbcType=DECIMAL}
  </select>
————————————————
版权声明:本文为CSDN博主「行云的逆袭」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/juligang320/article/details/82907147

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值