1.作用:实现创建一个接口后把mapper.xml由mybatis 生成接口的实现
类,通过调用接口对象就可以获取 mapper.xml 中编写的 sql.
2.后面 mybatis 和 spring 整合时使用的是这个方案.
3.实现步骤:
3.1 创建一个接口
3.1.1 接口包名和接口名与 mapper.xml 中<mapper>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"/> |
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> |
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" > |
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> |