mybatis参数传递

# mybatis获取参数值的两种方式

# ${}本质是字符串拼接
select * from t_user where username = ${username}
# 转化后(假设参数值是admin)
select * from t_user where username = admin # 显然错误,字符串要加''
# 正确写法
select * from t_user where username = '${username}'
# 转化后
select * from t_user where username = 'admin'

# #{}本质是占位符赋值
select * from t_user where username = #{username}
# 转化后
select * from t_user where username = ?

单个参数

// POJO类型: 参数占位符名称xxx和属性名一致
// Map集合: 参数占位符名称xxx和键名一致
// int,String等基本类型: #{xxx},参数占位符名称xxx可以任意写

// Collection: mybatis封装为Map集合, map.put("collection",collection集合)
// List: mybatis封装为Map集合, map.put("collection",list集合)或map.put("list",list集合)
// Array: mybatis封装为Map集合, map.put("array",数组)

多个参数

有多个参数的话,mybatis会将参数封装到Map集合中
Map集合键的名字,由mybatis给默认值

// map集合的大小是参数个数的两倍
map.put("arg0",参数值1)
map.put("arg1",参数值2)
map.put("param1",参数值1)
map.put("param2",参数值2)
<!--对于这样的一个接口方法-->
List<User> selectAll(String username, String password);

<select id="selectAll" resultType="User">
  <!--ok-->
  select * from user where username = #{arg0} and password = #{arg1};
  <!--error-->
  <!--Cause: org.apache.ibatis.binding.BindingException:-->
  <!--Parameter 'username' not found. Available parameters are [arg1, arg0, param1, param2]-->
  select * from user where username = #{username} and password = #{password};
</select>

@Param注解,使用指定的键名,将mybatis默认的arg键名替换掉

<!--自定义map集合中的键名-->
<!--解决sql中占位符 只能使用arg0和param1-->
List<User> selectAll(@Param("username") String username, @Param("password") String password);

<select id="selectAll" resultType="User">
    select * from user where username = #{username} and password = #{password};
</select>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值