mybatis的动态标签
if
if
选择标签
<if test=""></if>
where set trim
where
自动去除前面多余的and
or
等
select *
from order_details
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="orderId != null">
and order_id = #{orderId}
</if>
</where>
trim
和where差不多,但是功能更加强大
这样就和<where>一样,`prefixOverrides`表示去掉多余的前缀`and`
<trim prefix="where" prefixOverrides="and" suffix="" suffixOverrides="">
<if test="id != null">
and id = #{id}
</if> ....
</trim>
set
搭配update标签使用
<update id="updateAuthorIfNecessary">
update Author
#这里的set可以自动添加set 并且消除多余的逗号
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
也可以使用trim代替
<trim prefix="SET" suffixOverrides=",">
...
</trim>
choose when otherwise
choose
when
otherwise
这三个需要一起使用,类似java的swtich
choose表示开启一个选择
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
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>
bind
bind
用于给变量运算,并且保存中间结果
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>
sql include
这个不算动态标签,但是比较常用
sql
include
这两个也是一起使用的,sql
定义一个已经写好的片段,include
表示引用之前的sql
<sql id="selectColumn">id,orderId,productId</sql>
<select id="getxxx" resultMap="OrderDetailsMap">
select *
<include refid="selectColumn"/>
from order_details;
</select>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)