# 動態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(); } ``` 結果 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up