4.接口绑定-多参传递

MyBatis 接口绑定方案及多参数传递

  1. 作用:实现创建一个接口后把mapper.xml由mybatis生成接口的实现类,通过调用接口对象就可以获取 mapper.xml 中编写的 sql
  2. 后面 mybatis 和 spring 整合时使用的是这个方案
  3. 实现步骤:
  • 创建一个接口
    • 接口包名和接口名与 mapper.xml 中namespace相同
    • 接口中方法名和 mapper.xml 标签的 id 属性相同
  • 在 mybatis.xml 中使用进行扫描接口和 mapper.xml
  1. 代码实现步骤:
  • 在 mybatis.xml 中下使用(之前是<mapper resource…)
<mappers>
	<package name="com.buendia.mapper"/>
</mappers>
  • 在 com.buendia.mapper 下新建接口 public interface LogMapper { List selAll(); }
  • 在 com.buendia.mapper 新建一个 LogMapper.xml
    • namespace 必须和接口全限定路径(包名+类名)一致
    • id 值必须和接口中方法名相同
    • 如果接口中方法为多个参数,可以省略 parameterType
<mapper namespace="com.buendia.mapper.LogMapper"> 
	<select id="selAll" resultType="log"> 
        select * from log 
    </select> 
</mapper>
  1. 多参数实现办法
  • 在接口中声明方法 List selByAccInAccout(String accin,String accout);
  • 在 mapper.xml 中添加
    • #{}中使用 0,1,2 或 param1,param2
<!-- 当多参数时,不需要写 parameterType -->
<select id="selByAccInAccout" resultType="log" > 
	select * from log where accin=#{0} and accout=#{1}
</select>
  1. 可以使用注解方式
  • 在接口中声明方法
//mybatis 把参数转换为map了,其中@Param("key") 参数内容就是map的value 
//@param accin123
//@param accout3454235
//@return
List<Log> selByAccInAccout(@Param("accin") String accin123,@Param("accout") String accout3454235);
  • 在 mapper.xml 中添加
    • #{} 里面写@Param(“内容”)参数中内容
<!-- 当多参数时,不需要写 parameterType --> 
<select id="selByAccInAccout" resultType="log" > 
	select * from log where accin=#{accin} and accout=#{accout} 
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值