一、采用接口绑定方案的作用
创建一个接口后,MyBatis框架将mapper.xml通过反射机制生成接口的实现类,通过调用接口对象就可以获取mapper.xml中编写的sql。方便sql语句的调用,方便多个参数的传递,在未使用接口绑定方案前,传递多个参数要么是传递对象,要么是传递map。后面mybatis和spring整合时使用的是该方案。
二、实现步骤
<mappers>标签中使用<package>标签来配置mapper,name中的值为mapper文件所在的包名。
<mappers>
<package name="com.ccnu.mapper"/>
</mappers>
在mapper.xml文件所在包新建一个接口类,mapper.xml文件中的namespace必须和接口全限定路径(包名+类名)一致,sql语句的id值与接口中的方法名相同,返回值类型相对应,若为List类型,resultType中填写其中的泛型即可。
如果接口中方法包含多个参数,可以省略parameterType.
public interface LogMapper {
List<Log> selAll();
List<Log> selByAccInAccOut(String accin, String accout);
}
<mapper namespace="com.ccnu.mapper.LogMapper">
<!-- id要与接口的方法名一致 -->
<!-- resultType要与接口方法的返回值一致 -->
<select id="selAll" resultType="log">
select * from log
</select>
<!-- 当多参数时,不需要写parameterType -->
<!-- 基本参数类型用索引的方法来进行访问 -->
<select id="selByAccInAccOut" resultType="log" >
select * from log where accin=#{0} and accout=#{1}
</select>
</mapper>
注意:在传递参数中,xml文件中sql语句获得参数时,若传递的参数类型为基本数据类型,#{}括号中使用参数的索引来进行获取,#{0}则表示第一个参数,以此类推。也可以采用@param注解的方式,把参数转换为map,其中@param("")中为key,相应的参数内容为map的value,通过该方法,mapper.xml文件中可通过key来获取相应的参数值。
List<Log> selByAccInAccOut(@param("accin") String accin,@param("accout")
String accout);
<select id="selByAccInAccOut" resultType="log" >
select * from log where accin=#{accin} and accout=#{accout}
</select>
使用getMapper方法绑定接口,通过动态代理的方式得到接口的实现类,得到接口的实例化对象,再通过接口对象访问相应的方法。
LogMapper logMapper = session.getMapper(LogMapper.class);
List<Log> list = logMapper.selByAccInAccOut("1", "3");