当前位置: 首页 > news >正文

Mybatis引出的一系列问题-动态 SQL

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。

if
choose (when, otherwise)
trim (where, set)
foreach

1 if

使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。比如:

<select id="findActiveBlogWithTitleLike" resultType="Blog">SELECT * FROM BLOGWHERE state =ACTIVE<if test="title != null">AND title like #{title}</if>
</select>

这条语句提供了可选的查找文本功能。如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果(细心的读者可能会发现,“title” 的参数值需要包含查找掩码或通配符字符)。

如果希望通过 “title” 和 “author” 两个参数进行可选搜索该怎么办呢?首先,我想先将语句名称修改成更名副其实的名称;接下来,只需要加入另一个条件即可。

<select id="findActiveBlogLike" resultType="Blog">SELECT * FROM BLOG WHERE state =ACTIVE<if test="title != null">AND title like #{title}</if><if test="author != null and author.name != null">AND author_name like #{author.name}</if>
</select>

2 choose、when、otherwise

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句

还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员精选的 Blog)。

<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>

3 trim、where、set

前面几个例子已经方便地解决了一个臭名昭著的动态 SQL 问题。现在回到之前的 “if” 示例,这次我们将 “state = ‘ACTIVE’” 设置成动态条件,看看会发生什么。

<select id="findActiveBlogLike" resultType="Blog">SELECT * FROM BLOGWHERE<if test="state != null">state = #{state}</if><if test="title != null">AND title like #{title}</if><if test="author != null and author.name != null">AND author_name like #{author.name}</if>
</select>

如果没有匹配的条件会怎么样?最终这条 SQL 会变成这样:

SELECT * FROM BLOG
WHERE

这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:

SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’

这个查询也会失败。这个问题不能简单地用条件元素来解决。这个问题是如此的难以解决,以至于解决过的人不会再想碰到这种问题。

MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:

<select id="findActiveBlogLike" resultType="Blog">SELECT * FROM BLOG<where><if test="state != null">state = #{state}</if><if test="title != null">AND title like #{title}</if><if test="author != null and author.name != null">AND author_name like #{author.name}</if></where>
</select>

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:

  <update id="updateBatch" parameterType="java.util.List"><!--@mbg.generated-->update bs_factory_calendar<trim prefix="set" suffixOverrides=","><trim prefix="SET_TIME = case" suffix="end,"><foreach collection="list" index="index" item="item">when FACTORY_CALENDAR_ID = #{item.factoryCalendarId,jdbcType=VARCHAR} then #{item.setTime,jdbcType=VARCHAR}</foreach></trim><trim prefix="WEEK = case" suffix="end,"><foreach collection="list" index="index" item="item">when FACTORY_CALENDAR_ID = #{item.factoryCalendarId,jdbcType=VARCHAR} then #{item.week,jdbcType=VARCHAR}</foreach></trim></trim>where FACTORY_CALENDAR_ID in<foreach close=")" collection="list" item="item" open="(" separator=", ">#{item.factoryCalendarId,jdbcType=VARCHAR}</foreach></update>
  <insert id="insertOrUpdateSelective" parameterType="com.inspur.spring.pojo.BsFactoryCalendar"><!--@mbg.generated-->insert into bs_factory_calendar<trim prefix="(" suffix=")" suffixOverrides=","><if test="factoryCalendarId != null">FACTORY_CALENDAR_ID,</if><if test="setTime != null">SET_TIME,</if></trim>values<trim prefix="(" suffix=")" suffixOverrides=","><if test="factoryCalendarId != null">#{factoryCalendarId,jdbcType=VARCHAR},</if><if test="setTime != null">#{setTime,jdbcType=VARCHAR},</if></trim>on duplicate key update<trim suffixOverrides=","><if test="factoryCalendarId != null">FACTORY_CALENDAR_ID = #{factoryCalendarId,jdbcType=VARCHAR},</if><if test="setTime != null">SET_TIME = #{setTime,jdbcType=VARCHAR},</if></trim></insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.inspur.spring.pojo.BsFactoryCalendar"><!--@mbg.generated-->update bs_factory_calendar<set><if test="updateTime != null">UPDATE_TIME = #{updateTime,jdbcType=TIMESTAMP},</if><if test="comId != null">COM_ID = #{comId,jdbcType=VARCHAR},</if></set>where FACTORY_CALENDAR_ID = #{factoryCalendarId,jdbcType=VARCHAR}</update>

4 foreach

<select id="selectPostIn" resultType="domain.blog.Post">SELECT *FROM POST P<where><foreach item="item" index="index" collection="list"open="ID in (" separator="," close=")" nullable="true">#{item}</foreach></where>
</select>
http://www.lryc.cn/news/116168.html

相关文章:

  • Docker学习之构建Base Image
  • SFM(Structure from Motion)和NeRF(Neural Radiance Fields)
  • [Vue] Vue2和Vue3的生命周期函数
  • springboot集成分布式任务调度系统xxl-job(调度器和执行器)
  • 11_Vue3中的新的组件
  • 详解推送Git分支时发生的 cannot lock ref 错误
  • [国产MCU]-BL602开发实例-PWM
  • 【JMeter】 使用Synchronizing Timer设置请求集合点,实现绝对并发
  • 无法对watchdog.sys等系统文件删除,弯道修复,这里解决办法很简单
  • ClickHouse(九):Clickhouse表引擎 - Log系列表引擎
  • 3.1 计算机网络和网络设备
  • 值得中国人民大学与加拿大女王大学金融硕士中的金融人观看的五部电影
  • 【数据库】Redis可以替代Mysql吗
  • 5 指针与多维数组:多维数组在内存中的存储与指针的关系
  • Spring 创建 Bean 的三种方式
  • 软工导论知识框架(五)面向对象方法学
  • MyBatisPlus代码生成器
  • 文件传输软件常见问题解决办法大全
  • springboot工程测试临时数据修改技巧
  • Echarts 清空画布空白以及鼠标悬浮提示信息格式化问题
  • 数据结构入门:栈
  • 《UNUX环境高级编程》(14)高级I/O
  • 第5讲:如何构建类的方法
  • 【TypeScript】TS接口interface类型(三)
  • Python web实战之Django 的 RESTful API 设计详解
  • Python 程序设计入门(014)—— Python 的 Lambda 函数(匿名函数)
  • 【MySQL系列】表约束的学习
  • 低功耗LoRaWAN国产低功耗LoRa+RF射频前端芯片XD6500S
  • 【基础IO】文件系统 {磁盘的物理结构,存储结构,逻辑结构;CHS 和 LBA 寻址方式;磁盘分区和块组;文件inode;软硬链接}
  • 全角字符和半角字符