Mybatis (ParameterType) 如何传递多个不同类型的参数

14 篇文章 0 订阅

问题

当在写查询语句的时候需要传入多个参数的时候该怎么办呢?

方法一:不需要写parameterType参数

//传参
public List<XXXBean> getXXXBeanList(String xxId, String xxCode); 

// sql语句
<select id="getXXXBeanList" resultType="XXBean">
  select t.* from tableName where id = #{0} and name = #{1}  
</select> 

就不使用parameterType, 直接用索引,从0开始

方法二:基于注解(最简单)

//加注解传参
public List<XXXBean> getXXXBeanList(@Param("id")String id, @Param("code")String code);  

//sql语句
<select id="getXXXBeanList" resultType="XXBean">
  select t.* from tableName where id = #{id} and name = #{code}  
</select>  

@Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中(一般通过#{}的方式,${}会有sql注入的问题)

方法三:Map封装

//传参
HashMap <String,Object> map=new HashMap<String,Object>();
map.put("userName","zhangsan");
map.put("password","123456");
public List<XXXBean> getXXXBeanList(HashMap map);  

//sql语句
<select id="getXXXBeanList" parameterType="map" resultType="XXBean">
  select 字段... from XXX where id=#{userName} code = #{passWord}  
</select>  

方法四:List封装

//传入参数
public List<XXXBean> getXXXBeanList(List<String> list);  

//sql语句
<select id="getXXXBeanList" resultType="XXBean">
  select 字段... from XXX where id in
  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
    #{item}  
  </foreach>  
</select> 

最后

传递list和map在资源消耗上肯定远大于方法一和方法二,但是有一些特殊的情形需要传递list,比如你需要传递一个id集合并批量对id进行sql操作然后再返回等等。所以都需要了解。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Tan.]der

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

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

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

打赏作者

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

抵扣说明:

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

余额充值