1.if标签--单条件判断:判断完第一个条件,对下一个条件进行判断,看是否能满足条件,满足则执行

<select id="findByCondition" resultType="com.dyt.entity.Account">
        select * from account where 1=1
        <if test="name!=null and name!=''">
             and  name=#{name}
        </if>
        <if test="money!=null">
             and  money=#{money}
        </if>
    </select>

choose标签 多条件分支判断

假如第一个满足条件,则开始执行,并不会判断下一个条件,如第一个不满足则判断下一个,满足则执行

<select id="findByCondition02" resultType="com.dyt.entity.Account">
        select * from account where 1=1
        <choose>
             <when test="name!=null and name!=''">
                 and  name=#{name}
             </when>
            <when test="money!=null">
                and  money=#{money}
            </when>
            <otherwise>
                and isdeleted=0
            </otherwise>
        </choose>
    </select>

where标签

我们观察到上面的sql都加了 where 1=1 ,如果不使用where 1=1 那么你的动态sql可能会出错。 我们能不能不加where 1=1呢! 可以 那么我们就可以使用where标签,作用:可以自动为你添加where关键字,并且可以帮你去除第一个and |or

<select id="findByCondition" resultType="com.dyt.entity.Student">
        select * from Student
        <where>
            <if test="name!=null and name!=''">
                 and  name=#{name}
            </if>
            <if test="money!=null">
                 and  money=#{money}
            </if>
        </where>
    </select>

动态sql

set标签

这个配合if标签一起用,一般用在修改语句。如果传递的参数值为null,那么应该不修改该列的值

  <update id="update">
          update student
          <set>
             <if test="name!=null and name!=''">
                name=#{name},
             </if>
             <if test="age!=null">
                age=#{age},
             </if>
             <if test="sex!=null">
                 sex=#{sex},
             </if>
          </set>
          where id=#{id}
    </update>

foreach标签

循环标签.

查询:

<!-- select * from student where id in(2,3,5,7,0)
        如果你使用的为数组array  如果你使用的为集合 那么就用list
        collection:类型
        item:数组中每个元素赋值的变量名
        open: 以谁开始
        close:以谁结束
        separator:分割符

    -->
    <select id="findByIds" resultType="com.dyt.entity.Student">
        select * from student where id in
        <foreach collection="array" item="id" open="(" close=")" separator=",">
             #{id}
        </foreach>
    </select> 

删除:

 <delete id="batchDelete">
        <foreach collection="array" item="id" open="delete from student where  id in(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>

添加:

insert into student(name,isdeleted) values('ldh',0),('ldh2',0),('ldh4',0)
   <insert id="saveBatch">
        insert into student(name,isdeleted) values
        <foreach collection="list" item="acc" separator=",">
            (#{acc.name},#{acc.isdeleted})
        </foreach>
    </insert>

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐