象牙酥 Missing My Rainbow

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

1.说明

  所谓的MyBatis接口绑定,指的是实现创建一个接口后,把mapper.xml 由mybatis 生成接口的实现类,通过调用接口对象就可以获取mapper.xml 中编写的sql。在SSM框架中,MyBatis 和Spring 整合时使用的就是这个方案。

2.实现步骤

  1. 创建一个接口(Interface)
  • 创建的接口所在包名和接口名必须与mapper.xml文件中标签的namespace属性值相同
  • 接口中方法名和mapper.xml配置文件中标签的id属性相同
  1. 在mybatis.xml全局配置文件中配置标签,使得MyBatis进行扫描接口和mapper.xml

3.代码实现步骤:

  1. 在mybatis.xml 全局配置文件中下使用
<mappers>
	<package name="com.susu.mapper"/>
</mappers>
  1. 在com.susu.mapper 下新建接口
public interface LogMapper {
      List<Log> selAll();
}
  1. 在com.susu.mapper 新建一个LogMapper.xml
    注意:
  • namespace 必须和接口的全限定路径(包名+类名)一致
  • id 值必须和接口中方法名相同
  • 如果接口中方法为多个参数,可以省略parameterType
<mapper namespace="com.susu.mapper.LogMapper">
  <select id="selAll" resultType="log">
    select * from log
  </select>
</mapper>

4.多参数实现办法

  1. 在接口中声明方法
List<Log> selByAccInAccout(String accin,String accout);
  1. 在mapper.xml 中添加
    #{}中使用 0,1,2 或param1,param2
<!-- 当多参数时,不需要写parameterType -->
<select id="selByAccInAccout" resultType="log" >
   select * from log where accin=#{0}	and accout=#{1}
</select>

5. 可以使用注解方式

  1. 在接口中声明方法
List<Log> selByAccInAccout(@Param("accin") String accin123,@Param("accout") String accout3454235);

mybatis 把参数转换为map 了,其中@Param("key") 参数内容就是map 的value

  1. 在mapper.xml 中添加
    #{} 里面写@Param(“内容”)参数中内容
<!-- 当多参数时,不需要写parameterType -->
<select id="selByAccInAccout" resultType="log" >
   select * from log where accin=#{accin}	and accout=#{accout}
</select>
posted @ 2019-11-04 20:12  象牙酥  阅读(2461)  评论(0编辑  收藏  举报