MyBatis:簡述MyBatis映射文件中的參數傳遞

MyBatis:簡述MyBatis映射文件中的參數傳遞

1.方法中傳遞單個參數

public List<XXBean> getXXBeanList(String id);  

<select id="getXXXBeanList" parameterType="java.lang.String" resultType="XXBean">
  select * from tableName  where id= #{id}  
</select>  

其中方法名和select標籤的id一致,#{}中的參數名與方法中的參數名一致。select 後的字段列表要和bean中的屬性名一致, 如果不一致的可以用 as來補充,或者使用ResultMap自己配置。

2.方法中直接傳遞多個參數

public List<XXXBean> getXXXBeanList(String id, String name);  

<select id="getXXXBeanList" resultType="XXBean">
  select * from tableName where id = #{0} and name = #{1}  
</select>  

由於是多參數,所以就不能使用parameterType, 改用#{index}。是第幾個就用第幾個的索引,索引從0開始。

3.方法中通過Map封裝傳遞多個參數

public List<XXXBean> getXXXBeanList(HashMap map);  

<select id="getXXXBeanList" parameterType="java.util.HashMap" resultType="XXBean">
  select * from tableName where id=#{id} and name= #{name}  
</select>  

#{}中的參數名稱爲map中key的值。

4.方法中通過List封裝傳遞多個參數

public List<XXXBean> getXXXBeanList(List<String> list);  

<select id="getXXXBeanList" parameterType="java.util.List" resultType="XXBean">
  select * from tableName where id in
  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
    #{item}  
  </foreach>  
</select>  

foreach 最後的效果是select * from tableName where id in (‘1’,‘2’,‘3’,‘4’)。

5.方法中通過@Param註解傳遞多個參數

public List<XXXBean> getXXXBeanList(@Param("id")String id, @Param("name")String name);  

<select id="getXXXBeanList"  resultType="XXBean">
  select * from tableName where id=#{id} and name= #{name} 
</select>  

#{}中的參數名稱爲@Param註解中的值。

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