网站首页 > 博客文章 正文
MyBatis 令人喜欢的一大特性就是动态 SQL。在使用 JDBC 的过程中, 根据条件进行 SQL 拼接是很麻烦且很容易出错的。MyBatis 动态 SQL 的出现, 解决了这个麻烦。
MyBatis通过 OGNL 来进行动态 SQL 的使用的。目前, 动态 SQL 支持以下几种标签:
if
使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分,if 标签是我们最常使用的。在查询、删除、更新的时候很可能会使用到,必须结合 test 属性联合使用。
比如:
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
choose、when、otherwise
这三个标签需要组合在一起使用,类似于 Java 中的 switch、case、default。只有一个条件生效,也就是只要执行满足的条件 when,没有满足的条件就执行 otherwise,表示默认条件。
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
foreach
是对集合进行遍历(尤其是在构建 IN 条件语句的时候)
foreach标签主要有以下参数:
item :循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details,在list和数组中是其中的对象,在map中是value。
index :在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
猜你喜欢
- 2024-12-06 从asp.net到jsp:3分钟看透Jsp&Servlet
- 2024-12-06 MyBatis动态SQL:灵活的查询构建
- 2024-12-06 MyBatis常见问题分析
- 2024-12-06 MyBatis
- 2024-12-06 动态SQL实现原理一-动态SQL的使用
- 2024-12-06 Java面试——MyBatis
- 2024-12-06 面试官最常问的Mybatis面试题
- 2024-12-06 MyBatis详细面试题以及答案
- 2024-12-06 为什么90%的开发者放弃使用Hibernate,而选择MyBatis?
- 2024-12-06 mybatis动态SQL常用语法总结
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- powershellfor (55)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)