---
# System prepended metadata

title: 動態SQL之IF語句
tags: [Mybatis-動態SQL]

---

# 動態SQL之IF語句
###### tags: `Mybatis-動態SQL`

## IF
1.接口
```java=
    //查詢BOLG
    List<Blog> queryBlogIF(Map map);
```
2.xml文件加入if條件
就可以動態改變搜尋條件
```xml=
    <select id="queryBlogIF" parameterType="map" resultType="blog">
        <!--where 1 = 1 必定為真-->
        select * from mybatis.blog where 1 = 1
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </select>
```

3.測試類
```java=
 @Test
    public void queryBlogIF(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        HashMap hashMap = new HashMap();
        //放入不同參數實現動態查詢
        //例如想要用title或是author查詢，都可以直接操作
//        hashMap.put("title","first");
        hashMap.put("author","houdongun");


        List<Blog> blogs = mapper.queryBlogIF(hashMap);

        for(Blog blog:blogs){
            System.out.println(blog);
        }

        sqlSession.close();
    }
```
結果
![](https://i.imgur.com/FOxdp0b.png)
