mybatis传参问题总结

一、 传入单个参数
当传入的是单个参数时,方法中的参数名和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就会报错

猜你喜欢

转载自www.cnblogs.com/leexboo/p/10480955.html
今日推荐