MyBatis传入List集合查询数据问题怎么解决

寻技术 JAVA编程 / 其他编程 2023年11月21日 63

这篇文章主要介绍“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)

    关闭

    用微信“扫一扫”