mybatis动态生成sql语句简单实例

官网

https://mybatis.org/mybatis-3/zh/dynamic-sql.html

动态sql之if

概念 

If标签用于条件判断,当条件成立就附加<if></if>之间的sql语句,如果条件不成立就不附加<if></if>之间的sql语句。  

<if test=”xxx”> ......</if>

    <select id="getPersonByCodition" parameterType="Person"   resultType="Person">
        select *  from emp where 1=1
        <if test="ENAME!=null">
            and ENAME=#{ENAME}
        </if>
        <if test="JOB!=null">
             and JOB=#{JOB}
        </if>
        <if test="DEPTNO!=null">
            and DEPTNO=#{DEPTNO}
        </if>

动态sql之where标签

概念

<where>标签在sql语句后面附加where关键字,当where 标签中有成条件成立时就会附加where关键字,如where标签中没有任何条件成立则不会附加where关键字,where会忽略掉离他最近的一个无关的and or\

 

动态sql之choose、when、otherwises标签

概念

choose中有一个when成立就附加该条件,其它的when都不会被执行,如果所有的when都不成立就附加otherwise标签之间的sql语句

<select id="getPersonByCodition"  resultType="Person">
    select *  from emp
        <where>
            <choose>
                <when test="ENAME!=null">
                    and ENAME=#{ENAME}
                </when>
                <when test="DEPTNO!=null">
                    and DEPTNO=#{DEPTNO}
                </when>
              <otherwise>
                 and  1=1
              </otherwise>


            </choose>
        </where>
</select>

 

动态sql之set标签

概念

Set标签用于更新,set标签中有if条成立成就会附加该列,更新指定的列。会自动忽略掉最后一个与sql语句无关的逗号。

<select id="updatePerson" >
    update  emp
    <set>
        <if test="ENAME!=null">
            ENAME=#{ENAME},
        </if><if test="DEPTNO!=null">
            DEPTNO=#{DEPTNO},
        </if>

        <if test="MGR!=null">
              MGR=#{MGR},
        </if>
        <if test="JOB!=null">
                 JOB=#{JOB},
        </if>

    </set>
</select>

动态sql之foreach标签

概念

Collection: 指定集合的类型

Item: 定义一个变量用来接收集合中每个对象

Separator: 分隔符,当本次循环结束后,下次循环开始前附加分隔符

Open     附加字符 ,在循环开始前,附加字符串

Close     附加字符 ,在循环结束后,附加字符串

Index     集合的索引
批量添加,删除 修改

<insert id="addPersons" parameterType="list" useGeneratedKeys="true" keyProperty="EMPNO">

  insert into emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values
  <foreach collection="list" item="Person" separator="," open="(" close=")">
      #{Person.EMPNO},#{Person.ENAME},#{Person.JOB},#{Person.MGR},#{Person.HIREDATE},#{Person.SAL},#{Person.COMM},#{Person.DEPTNO}
  </foreach>


</insert>

动态sql之bind标签

拼装数据库 keyword 查找的关键字的字符串

<select id="getPersonBylikeName" resultType="Person">
<bind name="keyWord" value="'%'+ _parameter.getENAME()+'%'" ></bind>
    select * from emp where ENAME like #{keyWord}

</select>

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值