<select id="getBlogIF" parameterType="map" resultType="blog"> select * from blog <where> <if test="title != null"> title=#{title} </if> <if test="author != null"> and author=#{author} </if> </where> </select>
Preparing: select * from blog WHERE title=?
select * from blog WHERE author=?
这里的and被自动去掉了
select * from blog WHERE title=? and author=?
这里的and就没有被删除,很智能化
<select id="getBlogChoose" parameterType="map" resultType="blog"> select * from blog <where> <choose> <when test="title != null">/* 如果前面条件通过,后面的都不会实现 */ title=#{title} </when> <when test="author != null"> and author = #{author} </when> <otherwise> and views=#{views} </otherwise> </choose> </where> </select>
Mapper标签
<update id="updateBlog" parameterType="map"> update blog <set> <if test="title != null"> title=#{title}, </if> <if test="author != null"> author=#{author}, </if> </set> where views=#{views} </update>
实现
@Test public void updateBlog(){ SqlSession sqlSession = sqlSessionFactory.getsqlSession(); blogMapper mapper = sqlSession.getMapper(blogMapper.class); HashMap map = new HashMap(); map.put("title","微服务11"); map.put("author","小落11"); map.put("views",1000); mapper.updateBlog(map); sqlSession.commit();//注意增删改要提交事务 sqlSession.close();
sql结果(可以看到author后的,没有了)
update blog SET title=?, author=? where views=?