Mybatis动态sql查询

本文介绍使用MyBatis进行批量ID查询的两种方法:直接字符串拼接和foreach循环方式,并强调了安全性考虑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多业务情况下是根据不用id来查询需要select * from user where id in (1,2)这样的SQL。现在就提供两种方法实现

方法一:直接拼接插入

mapper.xml

<select id="findByIds" parameterType="java.lang.String" resultType="com.pojo.User">
        select * from user where id in (${value})
</select>
<!--
    注意点: ${}拼接符:字符串原样拼接,如果传入的参数是基本类型(string,long,double,int,boolean,float等),那么${}中的变量名称必须是value
  -->

@Test
    public void testfindByIds() throws Exception{
        SqlSession openSession = factory.openSession();
        //通过getMapper方法来实例化接口
        UserMapper mapper = openSession.getMapper(UserMapper.class);
        //方法一:用直接拼接
        List<String> list=new ArrayList<String>();
        list.add("1");
        list.add("3");
        String ids=String.join(",", list);
        List<User> result = mapper.findByIds(ids);  
        System.out.println(result);
    }

 方法二:foreach方式

mapper.xml

<select id="findByIds1" parameterType="java.util.List" resultType="com.pojo.User">
        select * from user
        <where>
            <if test="list.size() != 0">
                <!-- 
                foreach:循环传入的集合参数
                collection:传入的集合的变量名称
                item:每次循环将循环出的数据放入这个变量中
                open:循环开始拼接的字符串
                close:循环结束拼接的字符串
                separator:循环中拼接的分隔符
                 -->
                <foreach collection="list" item="id" open="id in(" close=")" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>
<!--

注意点 如果传入是list的话collection必须用list这个名字,而且parameterType必须是java.util.List的写法
-->

@Test
    public void testfindByIds1() throws Exception{
        SqlSession openSession = factory.openSession();
        //通过getMapper方法来实例化接口
        UserMapper mapper = openSession.getMapper(UserMapper.class);
        //方法二:传入List
        List<Integer> ids=new ArrayList<Integer>();
        ids.add(1);
        ids.add(3);
        List<User> result = mapper.findByIds1(ids); 
        System.out.println(result);
    }

拼接字符串的方式千万要保证传入的数据是正确,不然的话会存在SQL攻击!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值