Mybatis动态sql查询

很多业务情况下是根据不用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攻击!!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章