一、 傳入單個參數
當傳入的是單個參數時,方法中的參數名和sql語句中參數名一致即可
List<User> getUser(int id);<select id="getUser" parameterType="java.lang.Integer" resultType="com.lee.test.pojo.User">select * from t_user where id = #{id}
</select>
二、傳入的是多個參數
1、當傳入的是多個參數時,可以通過#{argindex}來對應參數,索引從0開始,其中sql語句中的參數順序與方法中的參數順序一致
List<User> getUser(int id, String name);<select id="getUser" resultType="com.lee.test.pojo.User">select * from t_user where id = #{arg0} and name =#{arg1}
</select>
2、使用@Param注解來指定對應的參數,其中@param中的參數與sql語句中的參數名一致
List<User> getUser(@param("id")int id, @param("name")String name);<select id="getUser" resultType="com.lee.test.pojo.User">select * from t_user where id = #{id} and name =#{name}
</select>
3、使用map封裝多個參數,其中map中的key和sql語句中的參數名一致
List<User> getUser(HashMap map);<select id="getUser" parameterType="hashMap" resultType="com.lee.test.pojo.User">select * from t_user where id = #{id} and name =#{name}
</select>
三、傳入的參數是一個實體類
當傳入的是一個實體類,mybatis會根據實體類中字段自動與sql中參數關聯
List<User> getUser(User user);<select id="getUser" parameterType="com.lee.test.pojo.User" resultType="com.lee.test.pojo.User">select * from t_user where id = #{id} and name =#{name}
</select>
四、當傳入的參數包含了數組
如果傳入的參數中包括了數組,可以使用mybatis中動態sql的foreach標簽
標簽屬性說明:
(1)collection :collection屬性對應有三種,list,array和map
(2)item : 在迭代每一個元素時起的別名,與#{}參數名一致
(3)index :這個屬性用來指定用來訪問迭代集合下標的名稱。如:index="myIndex",則#{myIndex}用來訪問當前迭代的下標,下標從0開始。
(4)open :拼接字符串的前綴,如"("
(5)close :拼接字符串的后綴,如")"
(6)separator :分隔符,表示迭代時每個元素之間的分隔符號,如","
1、如果傳入的是一個list
List<User> getUser(List<Integer> ids);<select id="getUser" resultType="com.lee.test.pojo.User">select * from t_user where id in<foreach collection="list" item="id" index="index" open="(" close=")" separator=",">#{id}</foreach></select>
如果傳入的list ids為1,2,3
這句sql語句相當于 select * from t_user where id in (1,2,3)
2、如果傳入的是一個array
List<User> getUser(int[] ids);<select id="getUser" resultType="com.lee.test.pojo.User">select * from t_user where id in<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">#{id}</foreach></select>
如果傳入的int[] ids為1,2,3
這句sql語句相當于 select * from t_user where id in (1,2,3)
3、如果傳入的是一個map
在開發過程中會遇到既要傳入一個String,又要傳入一個list,這時我們就可以把把這個String和list封裝成一個map
//定義一個list
List ids = new ArrayList();
ids.add(1);
ids.add(2);
ids.add(3);
//將list和string放到map
HashMap map = new HashMap();
map.put("name", name);
map.put("ids", ids);//mapper.java
List<User> getUser(HashMap map);//mapper.xml
<select id="getUser" parameterType="java.util.HashMap" resultType="com.lee.test.pojo.User">select * from t_user where name = #{name} and id in<foreach collection="ids" item="id" index="index" open="(" close=")" separator=",">#{id}</foreach>
</select>
這里collection的值是map中list的key值,如果直接寫list或者array就會報錯