本文整理了 mybatis 中进行 crud 操作时常用的动态 sql 标签及其使用方式,适合初学者查阅和实践。
1.<if>:条件判断
用于在满足条件时拼接 sql 片段。
<select id="selectuser" parametertype="map" resulttype="user">
select * from user
<where>
<if test="name != null and name != ''">
name = #{name}
</if>
<if test="age != null">
and age = #{age}
</if>
</where>
</select>
test是唯一属性,使用 ognl 表达式判断变量是否存在或满足条件。
2.<choose> / <when> / <otherwise>:类似 switch-case
用于多分支选择。
<select id="getuser" parametertype="map" resulttype="user">
select * from user
<where>
<choose>
<when test="id != null">
id = #{id}
</when>
<when test="name != null">
name = #{name}
</when>
<otherwise>
1 = 1
</otherwise>
</choose>
</where>
</select>
3.<where>:自动处理where和and
自动去掉首个 and 或 or,并在需要时自动加上 where。
<where>
<if test="name != null">name = #{name}</if>
<if test="age != null">and age = #{age}</if>
</where>
4.<set>:用于update自动拼接字段
会自动去除最后一个逗号,并加上 set。
<update id="updateuser" parametertype="user">
update user
<set>
<if test="name != null">name = #{name},</if>
<if test="age != null">age = #{age},</if>
</set>
where id = #{id}
</update>
5.<foreach>:用于批量操作(插入、删除、in)
批量插入:
<insert id="batchinsert" parametertype="list">
insert into user (name, age) values
<foreach collection="list" item="user" separator=",">
(#{user.name}, #{user.age})
</foreach>
</insert>
in查询:
<select id="selectbyids" parametertype="list" resulttype="user">
select * from user where id in
<foreach collection="list" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
6.<trim>:自定义修剪逻辑(替代<set>/<where>)
用于去除开头或结尾的多余 sql 关键词。
<update id="updateuser" parametertype="user">
update user
<trim prefix="set" suffixoverrides=",">
<if test="name != null">name = #{name},</if>
<if test="age != null">age = #{age},</if>
</trim>
where id = #{id}
</update>
到此这篇关于mybatis crud 常用动态 sql 标签整理的文章就介绍到这了,更多相关mybatis crud 动态 sql 内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论