mybatis传入多个参数以及list集合参数

  • Post author:
  • Post category:其他


mybatis进行传参的时候,可能传入单个参数,也可能传入对象参数,也可能传入list集合参数;

在接口传参数的时候不免会用到一个注解,@Param注解。


1.使用@Param注解

当以下面的方式进行写SQL语句时:

@Select(“select column from table where userid = #{userid} “)

public int selectColumn(int userid);

当你使用了使用@Param注解来声明参数时,如果使用 #{} 或 ${} 的方式都可以。

@Select(“select column from table where userid = ${userid} “)

public int selectColumn(@Param(“userid”) int userid);

当你不使用@Param注解来声明参数时,必须使用使用 #{}方式。如果使用 ${} 的方式,会报错。

@Select(“select column from table where userid = ${userid} “)

public int selectColumn(@Param(“userid”) int userid);


2.不使用@Param注解

不使用@Param注解时,参数只能有一个,并且是Javabean。在SQL语句里可以引用JavaBean的属性,而且只能引用JavaBean的属性。

// 这里id是user的属性

@Select(“SELECT * from Table where id = ${id}”)

Enchashment selectUserById(User user);

1.对象参数

当传入对象参数的时候,其实就相当于传入了多个参数,参数都封装在对象属性中,这时候在xml中调用该参数的时候我们只需要通过该方式:#{对象.属性名}就可以调用到对应的属性的值。

dao层示例

public List<user> getUserInformation(@Param(“user”) User user);

xml映射对应示例

<select id="getUserInformation" parameterType="com.github.demo.vo.User" resultMap="userMapper">  

        select   

        <include refid="User_Base_Column_List" />  

        from mo_user t where 1=1  

                      <!-- 因为传进来的是对象所以这样写是取不到值得 -->  

            <if test="user.userName!=null  and user.userName!=''">   and   t.user_name = #{user.userName}  </if>  

            <if test="user.userAge!=null  and user.userAge!=''">   and   t.user_age = #{user.userAge}  </if>  

    </select>  

2.单一属性参数

当传入单一属性的参数的时候只需要通过#{param中的value}就可以调用到该参数

dao层示例

Public User selectUser(@param(“userName”) String name,@param(“userpassword”) String password);

xml映射对应示例

<select id=" selectUser" resultMap="BaseResultMap">  

   select  *  from user_user_t   where user_name = #{userName,jdbcType=VARCHAR} and user_password=#{userPassword,jdbcType=VARCHAR}  

</select>

3.list集合参数

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

<select id=”getXXXBeanList” resultType=”XXBean”>

select 字段… from XXX where id in

<foreach item=”item” index=”index” collection=”list” open=”(” separator=”,” close=”)”>

#{item}

</foreach>

</select>

foreach 最后的效果是select 字段… from XXX where id in (‘1′,’2′,’3′,’4’)

foreach标签详解:

属性 描述

item
循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。具体说明:在list和数组中是其中的对象,在map中是value。该参数为必选。

collection
collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合。该参数为必选。

separator
元素之间的分隔符,例如在in()的时候,separator=”,”会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。

open
foreach代码的开始符号,一般是(和close=”)”合用。常用在in(),values()时。该参数可选。

close
foreach代码的关闭符号,一般是)和open=”(“合用。常用在in(),values()时。该参数可选。

index
在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。



版权声明:本文为weixin_40159122原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。