上篇以及学习了动态sql的if用法,这里学习choose、when、otherwise的用法。
先介绍<where>标签的用法:
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
这里直接上mapper.xml代码
<select id="queryBlogChoose" parameterType="map" resultType="com.lizheng.pojo.Blog">select * from mybatis.blog<where><choose><when test="title != null">and title = #{title}</when><when test="author != null">and author = #{author}</when><otherwise>views = #{views}</otherwise></choose></where></select>
测试类
@Testpublic void queryBlogChooseTest(){SqlSession sqlSession = MybatisUtils.getSqlSession();BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);HashMap map = new HashMap();map.put("author","狂神说");map.put("title","Mybatis");mapper.queryBlogChoose(map);sqlSession.commit();sqlSession.close();}
==============================================================================================================
增加set用法
<update id="queryBlogInsert" parameterType="map">update mybatis.blog<set><if test="title != null">title = #{title},</if><if test="author != null">author = #{author},</if><if test="views != null">views = #{views},</if></set>where id = #{id}</update>