动态SQL常用标签
2022/1/27 2:04:18
本文主要是介绍动态SQL常用标签,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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=?
这篇关于动态SQL常用标签的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-20测试人员都是画画大神,让我看看谁还不会用代码图?
- 2024-05-20年薪百万的程序员都在用的摸鱼方式……
- 2024-05-19永别了,微服务架构!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了