MyBatis动态sql语句(OGNL语法)

2020-09-25 16:27 更新

1、if

  1. <select id="select"
  2. resultType="Blog">
  3. SELECT * FROM BLOG
  4. WHERE state = ‘ACTIVE’
  5. <if test="title != null">
  6. AND title like #{title}
  7. </if>
  8. <if test="name!= null">
  9. AND name like #{title}
  10. </if>
  11. </select>

2、where

像上面的那种情况,如果where后面没有条件,然后需要直接写if判断(开头如果是 and / or 的话,会去除掉)

  1. <select id="select"
  2. resultType="Blog">
  3. SELECT * FROM BLOG
  4. <where>
  5. <if test="title != null">
  6. AND title like #{title}
  7. </if>
  8. <if test="name!= null">
  9. AND name like #{title}
  10. </if>
  11. <where>
  12. </select>

3、choose(when、otherwise) 

choose 相当于 java 里面的 switch 语句。otherwise(其他情况)

  1. <select id="findActiveBlogLike"
  2. resultType="Blog">
  3. SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  4. <choose>
  5. <when test="title != null">
  6. AND title like #{title}
  7. </when>
  8. <when test="author != null and author.name != null">
  9. AND author_name like #{author.name}
  10. </when>
  11. <otherwise>
  12. AND featured = 1
  13. </otherwise>
  14. </choose>
  15. </select>

4、tirm

tirm

prefix:前缀prefixoverride:去掉第一个and或者是or

select * from test
<trim prefix="WHERE" prefixoverride="AND丨OR">
      <if test="a!=null and a!=' '">AND a=#{a}<if>
      <if test="b!=null and b!=' '">AND a=#{a}<if>
</trim>


5、set

set 元素主要是用在更新操作的时候,如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。

  1. <update id="dynamicSetTest" parameterType="Blog">
  2. update t_blog
  3. <set>
  4. <if test="title != null">
  5. title = #{title},
  6. </if>
  7. <if test="content != null">
  8. content = #{content},
  9. </if>
  10. <if test="owner != null">
  11. owner = #{owner}
  12. </if>
  13. </set>
  14. where id = #{id}
  15. </update>

 6、foreach

foreach主要用在构建in条件中

  1. <select id="dynamicForeachTest" resultType="Blog">
  2. select * from t_blog where id in
  3. <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
  4. #{item}
  5. </foreach>
  6. </select>

open separator close

相当于是in (?,?,?)

 如果是个map怎么办

  1. <select id="dynamicForeach3Test" resultType="Blog">
  2. select * from t_blog where title like "%"#{title}"%" and id in
  3. <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
  4. #{item}
  5. </foreach>
  6. </select>

collection对应map的键,像这样

  1. List<Integer> ids = new ArrayList<Integer>();
  2. ids.add(1);
  3. ids.add(2);
  4. ids.add(3);
  5. ids.add(6);
  6. ids.add(7);
  7. ids.add(9);
  8. Map<String, Object> params = new HashMap<String, Object>();
  9. params.put("ids", ids);


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部