Mybatis 传递参数类型为List的取值如何解决

今天就跟大家聊聊有关Mybatis 传递参数类型为List的取值如何解决,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

问题描述:

参数传递为List时:

当传递一个 List 实例或者数组作为参数对象传给 Mybatis。此时,Mybatis 会自动将它包装在一个 Map 中,用名称在作为键。List 实例将会以“list” 作为键,而数组实例将会以“array”作为键。所以,当我们传递的是一个List集合时,mybatis会自动把我们的list集合包装成以list为Key值的map。

DAO 层:

List<User> selectUserByIDs( List IDs);

XML文件:

<select id="selectUserByIDs" parameterType="java.util.List" resultType="user">
    select * from user
    <where>
      <if test="IDs != null and IDs.size() >0">
        <foreach collection="IDs" open=" and id in (" close=")" item="uid" separator=",">
          #{uid}
        </foreach>
      </if>
    </where>
</select>

报错信息:

org.apache.ibatis.binding.BindingException: Parameter ‘IDs' not found. Available parameters are [collection, list]

解决方法:

方法一:将我们的XML中collection属性值直接设置为list

DAO 层:

List<User> selectUserByIDs( List IDs);

XML文件:

<select id="selectUserByIDs" parameterType="java.util.List" resultType="user">
    select * from user
    <where>
      <if test="list != null and list.size() >0">
        <foreach collection="list" open=" and id in (" close=")" item="uid" separator=",">
          #{uid}
        </foreach>
      </if>
    </where>
</select>

方法二: 利用注解@Param指定我们的入参名称

DAO层:

List<User> selectUserByIDs(@Param("IDs") List IDs);

XML文件:

<select id="selectUserByIDs" parameterType="java.util.List" resultType="user">
    select * from user
    <where>
      <if test="IDs != null and IDs.size() >0">
        <foreach collection="IDs" open=" and id in (" close=")" item="uid" separator=",">
          #{uid}
        </foreach>
      </if>
    </where>
</select>

看完上述内容,你们对Mybatis 传递参数类型为List的取值如何解决有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。