动态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=?
posted @   小罗要有出息  阅读(389)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
点击右上角即可分享
微信分享提示