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攻擊!!!!

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