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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章