1 where标签
1.1若满足条件的首条sql语句前面没有‘and’或者‘or’,Mybatis会自动拼接sql语句,如果满足条件的首条sql语句前面有‘and’或者‘or’,Mybatis会自动的去掉‘and’或者‘or’
| <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> |
1.2 当只有title不为空时,运行结果的sql语句
| Preparing: select * from blog WHERE title=? |
1.3 当只有anthor不为空时,运行结果的sql语句
| select * from blog WHERE author=? |
这里的and被自动去掉了
1.4 当title和anthor不为空时,运行结果的sql语句
| select * from blog WHERE title=? and author=? |
这里的and就没有被删除,很智能化
2 choose标签(类似于Java中的swtich选择结构)
| <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> |
3 set标签(主要用于数据更新) set标签会自动加上set并且会去除多余的‘,’
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=? |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?