MyBatis传入List集合查询数据问题

2023-02-09

这篇文章主要介绍了MyBatis传入List集合查询数据问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

目录
  • MyBatis传入List集合查询数据
    • 主要有两点问题
  • MyBatis传入List集合批量删除
    • 总结

      MyBatis传入List集合查询数据

      使用的是SSM框架,数据库是MySQL,做查询的时候传入List集合,使用SQL语句的in方式查询数据

      主要有两点问题

      我的List集合是利用的另外一个语句查询出来的,传入参数是int类型,返回值是int类型的List集合:

      List<Integer> select(Integer id);
      <select id="select" resultType="java.util.List"
          parameterType="java.lang.Integer">
          select id
          from section
          where status='A'
          and unit_id=#{id,jdbcType=INTEGER}
      </select>

      这是我第一次的时候使用的返回值类型(java.util.List),这种情况下在我执行的时候会报错:java.lang.UnsupportedOperationException

      其实这里如果我们是要返回指定类型的集合直接写java.lang.Integer(int类型)java.lang.String(字符串)等等就可以了,当然也可以自定义一个resultMap

      <select id="select" resultType="java.lang.Integer"
          parameterType="java.lang.Integer">
          select id
          from section
          where status='A'
          and unit_id=#{id,jdbcType=INTEGER}
      </select>

      上面是通过一个id查询出List集合,下面是将查到的这个List集合放入查询条件中:

      List<Test> selectById(List<Integer> id);
      <select id="selectById" parameterType="java.util.List"
          resultMap="BaseResultMap">
          select * from test
          where status = 'A'
          and id in
          <foreach collection="list" index="index" item="item" open="("
              separator="," close=")">
              #{item}
          </foreach>
      </select>

      上述的查询语句可以整合在一个sql语句中,这里为了创造list数据所以分开了。

      使用foreach 语句循环集合中的数据,item就是循环到的数据,如果你是一个复杂类型的数据做批量插入的话可以使用item.属性名 的方式获取对应值,类似于java的foreach循环语句,某些时候可能传入的是Array数组,毕竟都说Array比List效率高,这种时候和上述方法类似,也是foreach语句。具体的分析后续更新。

      MyBatis传入List集合批量删除

      Model

      public class FastDFSModel {
          private String pathId;
          private String modelId;
          private String csvpath;
          private String resultpath;
          private String updatetime;
          }

      Dao

      import org.apache.ibatis.annotations.Param;
       void deleteDateById(@Param("list") List<FastDFSModel> deleteList);

      mapper

      其中parameterType写为list

      foreach 中的collection写为"list"

      item 为遍历的每一项,代表着model

      在变量中用#{item.pathId}来获取值

      此业务为通过id进行删除

      其中open="(" separator="," close=")"为拼接的in查询,把id用逗号拼接起来

       <delete id="deleteDateById" parameterType="java.util.List">
              delete from T_FASTDFS_PATH t where t.path_id in
              <foreach item="item" collection="list" open="(" separator="," close=")">
                  #{item.pathId,jdbcType=VARCHAR}
              </foreach>
          </delete>

      控制台打印如下

      delete from T_FASTDFS_PATH t where t.path_id in ( ? , ? , ? ) 
       PreparedStatement - ==> Parameters: 2(String), 1(String), 3(String)

      总结

      以上为个人经验,希望能给大家一个参考,也希望大家多多支持北冥有鱼。

      《MyBatis传入List集合查询数据问题.doc》

      下载本文的Word格式文档,以方便收藏与打印。