MyBatis增删改查02

MyBatis的动态Sql

动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
 
使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。
 
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少

常用的几个标签标签:

一、基础标签

<select></select>

<delete></delete>

<insert></insert>

<update>

<set></set>

</update>

二、条件判断标签

<where></where>

<if></if>

<when></when>

<forch></forch>

MyBatis标签的应用

一、MyBatis的基础标签应用:

1、添加

<insert id="addEmp" parameterType="org.example.entity.Emp">
    insert into emp(ename,status,createtime,deptno,pwd)
    values(#{ename},#{status},#{createtime},#{deptno},#{pwd})
</insert>

2、删除

<delete id="deleteEmp">
    delete from emp where empno=#{empno}
</delete>

3、查询

<select id="findAll"  resultType="org.example.entity.Emp" >
    select * from emp
</select>

4、修改

update id="updateEmp">

    update emp set ename=#{ename} where empno=#{empno}
</update>

二、

MyBatis条件标签的用法

1、多条数据新增  用到了forch循环

<insert id="addArrUser">
    insert into userinfo(username,password,createDate) values
    <foreach collection="array" separator="," item="i" >
        (#{i.username},#{i.password},#{i.createDate})
    </foreach>
</insert>

2、单条数据查询  where条件和if判断

<select id="findAll" resultType="org.example.entity.TabUser">

        select * from tab_user
        <where>
            <if test="name!=null and name!=''">
                and name=#{name}
            </if>
            <if test="pwd!=null and pwd!=''">
                and pwd=#{pwd}
            </if>

<!--             判断 中 属性写什么    #{} -->
            <if test="id!=null and id!=''">
                and id=#{id}
            </if>
        </where>

    </select>

3、修改  判断一下数据是不是为空用where和if标签判断以及自带的set标签

<update id="updUser">]
    update tab_user
   <set>
         <if test=" name !=null and name!=''">
             name=#{name},
         </if>
       <if test="pwd!=null and pwd!=''">
            pwd=#{pwd},
       </if>
       <if test="address!=null and address!=''">
           address=#{address},
       </if>
       <if test="date!=null and date!=''">
           date=#{date},
       </if>
   </set>

    <where>
        id=#{id}
    </where>


</update>

4、多条数据删除用forch循环

<delete id="delUsers">
    delete from tab_user  where id in

    <foreach collection="list" separator="," item="i" open="("  close=")" >
        #{i}
    </foreach>



</delete>

  • 13
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值