Mybatis动态 SQL 大全

1. If 语句

<select id="queryBlogIf" parameterType="map" resultType="blog">
 select * from blog where
 <if test="title != null">
  title = #{title}
 </if>
 <if test="author != null">
  and author = #{author}
 </if>
</select>

 

2. Where语句

<select id="queryBlogIf" parameterType="map" resultType="blog">
 select * from blog
 <where>
  <if test="title != null">
   title = #{title}
  </if>
  <if test="author != null">
   and author = #{author}
  </if>
 </where>
</select>

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

 

3. Set语句

<!--注意set是用的逗号隔开-->
<update id="updateBlog" parameterType="map">
 update blog
 <set>
  <if test="title != null">
   title = #{title},
  </if>
  <if test="author != null">
   author = #{author}
  </if>
 </set>
 where id = #{id};
</update>

 

4. Choose语句

<select id="queryBlogChoose" parameterType="map" resultType="blog">
 select * from blog
 <where>
  <choose>
   <when test="title != null">
    title = #{title}
   </when>
   <when test="author != null">
    and author = #{author}
   </when>
   <otherwise>
    and views = #{views}
   </otherwise>
  </choose>
 </where>
</select>

5. Foreach语句

<select id="queryBlogForeach" parameterType="map" resultType="blog">
 select * from blog
 <where>
  <!--
  collection:指定输入对象中的集合属性
  item:每次遍历生成的对象
  open:开始遍历时的拼接字符串
  close:结束时拼接的字符串
  separator:遍历对象之间需要拼接的字符串
  select * from blog where 1=1 and (id=1 or id=2 or id=3)
  -->
  <foreach collection="ids" item="id" open="and (" close=")"
  separator="or">
   id=#{id}
  </foreach>
 </where>
</select>

 

6. SQL片段

<sql id="if-title-author">
 <if test="title != null">
  title = #{title}
 </if>
 <if test="author != null">
  and author = #{author}
 </if>
</sql>

 

引用SQL片段:

<select id="queryBlogIf" parameterType="map" resultType="blog">
 select * from blog
 <where>
  <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace-->
  <include refid="if-title-author"></include>
  <!-- 在这里还可以引用其他的 sql 片段 -->
 </where>
</select>

7. Bind元素

bind 元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。比如:

<select id="selectBlogsLike" resultType="Blog">
  <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
</select>
 
posted @   KLAPT  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示