mybatis常用的动态语句简单总结,具体运用中需要加深对数据库运用的理解
foreach:
item表示集合中每一个元素进行迭代时的别名,常用为:“item”
index迭代对象是数组或者列表时,标识当前迭代的次数,item是当前迭代获取的值。当使用字典或者map时,index是键,item是值。常用#{}结合使用
open表示该语句以什么开始,常用为"("
separator表示在每次进行迭代之间以什么符号作为分隔符,常用","
close表示以什么结束,常用为")"
传参为List时:
<select id="gery" parameterType="java.util.List" resultType="Blog">
select * from xkc_blog where id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
传参为arraylist数组时:
<select id="gery" parameterType="java.util.ArrayList" resultType="Blog">
select * from xkc_blog where id in
<foreach collection="arrayList" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
传参为Map数组时:
java代码片段,
Map<String, Object> param = new HashMap<String, Object>();
param.put("xkc", xkc);
param.put("myBlog", myBlog);
siteOperationDao.addMyBlogByXkc(param);
mybatis代码:
<select id="gery" parameterType="java.util.ArrayList" resultType="Blog">
select * from xkc_blog where id in
<foreach collection="myBlog" item="blog" index="index" separator=",">
(#{xkc.name}, #{ myBlog.title})
</foreach>
</select>
if的用法:
它的用法简单,一般常用嵌套在where后或者foreach循环中作为判断
<select id="gery" parameterType="java.util.ArrayList" resultType="Blog">
select * from xkc_blog
<if test="id != null">WHERE id = #{id}</if>
</select>
set用法:
update和update语句中没有使用 if 标签时,如果有一个参数为 null,都会导致错误。SET关键字去除条件末尾不相关的冒号。set中如果某项为null,则不更新。
<update id="gery" parameterType="java.util.ArrayList" resultType="Blog">
insert into xkc_blog
<set>
name = #{name},
<if test="id != null">id=#{id},</if>
</set>
</update>
在insert和update语句中,tirm去除条件末尾不相关的冒号
<insert id="gery" parameterType="java.util.ArrayList" resultType="Blog">
insert into xkc_blog
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="name != null">name,</if>
</trim>
</insert>
这篇博客详细总结了MyBatis中常用的动态SQL语句,包括foreach用于处理数组或集合,if用于条件判断,set在更新语句中的应用,以及trim在去除多余逗号上的作用。通过实例展示了如何在SQL查询和更新中灵活使用这些语句,以提高代码的可读性和效率。对于理解和使用MyBatis动态SQL有很好的参考价值。
1664

被折叠的 条评论
为什么被折叠?



