Python 官方文档:入门教程 => 点击学习
目录基本流程IF,WhereSetChoose(when,otherwise)sql片段总结什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句 基本流程
什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
1,数据库准备一张表
2,导包
3,编写核心配置文件
4,编写实体类
5,编写实体类对应的Mapper和Mapper.xml文件
6,在核心配置文件中注册Mapper.xml
7,测试
开启自动驼峰命名规则映射
<!--开启驼峰命名映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
即在数据库中为create_time对应Java实体类属性createTime
<select id="queryListIf" 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>
Where的作用:当至少有一个满足条件时添加Where,且会判断后面加的第一条语句,若是and开头,则会自动将这个and删除
本质上还是在拼接SQL,上述当没有满足条件时查询blog表中的所有,当满足条件时,则拼接SQL
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
Set的作用:至少有一个满足条件时添加Set,且会判断后面加的最后的语句,若是",“结尾,则会自动将这个”,"删除
<select id="queryNoLimit" 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 `view` = #{view}
</otherwise>
</choose>
</where>
</select>
choose(when,otherwise)类似与Java中的switch(case,default),choose进入选择,when当什么什么时,进行条件判断,若满足条件,则执行条件中的内容,后面的when,otherwise将不再执行,otherwise当所有when都不满足条件时执行
ForEach
<select id="queryBlogById" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="(" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
上述为,一个集合ids存储id的内容,根据这个集合查询所包含的id,open为开始,close为结束,separator为分隔符
才用map.put(“ids”,list)的方式导入集合
建议:现在Mysql中写出完整的sql,再对应的去修改即可
将一些功能的部分抽取出来方便复用
使用SQL标签抽取公共的部分
<sql id="titleAuthor">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
在需要的地方使用include标签引用即可
<select id="queryListIf" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="titleAuthor"></include>
</where>
</select>
注意事项:
1.最好基于单表来定义SQL片段
2.不要存在where标签
所谓的动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式去排列组合就可以了
到此这篇关于mybatis动态SQL的示例代码的文章就介绍到这了,更多相关Mybatis动态SQL内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Mybatis动态SQL的示例代码
本文链接: https://www.lsjlt.com/news/155694.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0