1.作用:
实现创建一个接口后把mapper.xml由mybatis 生成接口的实现 类,通过调用接口对象就可以获取 mapper.xml 中编写的 sql.
2.后面 mybatis 和 spring 整合时使用的是这个方案.
3.实现步骤:
3.1 创建一个接口
3.1.1 接口包名和接口名与 mapper.xml 中<maapper>namespace 相同
3.1.2 接口中方法名和 mapper.xml 标签的 id 属性相同
3.2 在 mybatis.xml 中使用<package>进行扫描接口和 mapper.xml
4.代码实现步骤:
4.1 在 mybatis.xml 中<mappers>下使用<package>标签(只需要写其所在的完整包名,不需要写类名)
<mappers>
<package name="com.bjsxt.mapper"/>
</mappers>
4.2 在 com.bjsxt.mapper 下新建接口
public interface LogMapper {
List<Log> selAll();
}
4.3 在 com.bjsxt.mapper 新建一个 LogMapper.xml
4.3.1 namespace 必须和接口全限定路径(包名+类名)一致
4.3.2 id 值必须和接口中方法名相同
4.3.3 如果接口中方法为多个参数,可以省略 parameterType
<mapper namespace="com.bjsxt.mapper.LogMapper">
<select id="selAll" resultType="log">
select * from log
</select>
</mapper>
4.4测试调用
public static void main(String[] args) throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
/*
* 接口,为什么能实例化?
*
* 需要给接口一个实例化对象.
*
* 使用的JDK的动态代理设计模式.
* 面向接口的代理设计模式(必须有接口)
*
*/
// LogMapper logMapper = session.getMapper(LogMapper.class);
// List<Log> list = logMapper.selAll();
// for (Log log : list) {
// System.out.println(log);
// }
//使用的方式发生了改变 session.getMapper(接口名.class)
LogMapper logMapper = session.getMapper(LogMapper.class);
//直接调用相关方法
List<Log> list = logMapper.selByAccInAccout("3", "1");
for (Log log : list) {
System.out.println(log);
}
session.close();
System.out.println("程序执行结束");
}
5.多参数实现办法
5.1 在接口中声明方法
List<Log> selByAccInAccout(String accin,String accout);
5.2 在 mapper.xml 中添加
5.2.1 #{}中使用 0,1,2 或 param1,param2
<!-- 当多参数时,不需要写 parameterType -->
<select id="selByAccInAccout" resultType="log" >
select * from log where accin=#{0} and accout=#{1}
</select>
6.可以使用注解方式
6.1 在接口中声明方法
/**
* mybatis 把参数转换为 map 了,其中@Param("key") 参数内
容就是 map 的 value
* @param accin123
* @param accout3454235
* @return
*/
List<Log> selByAccInAccout(@Param("accin") String
accin123,@Param("accout") String accout3454235);
6.2 在 mapper.xml 中添加
6.2.1 #{} 里面写@Param(“内容”)参数中内容
<!-- 当多参数时,不需要写 parameterType -->
<select id="selByAccInAccout" resultType="log" >
select * from log where accin=#{accin} and
accout=#{accout}
</select>