动态SQL

一.if元素

相当于java的if,主要用来判断是否为空

<select id="ifsql" resultType="User">
    select  *  
    from user
    where
    <if test="id!=null">
        id=#{id}
    </if>
    <if test="name!=null">
        and name=#{name}
    </if>
    <if test="addr!=null">
        and addr=#{addr}
    </if>
</select>

二.choose....when.....otherwise.....元素

多重判断。

<select id="findRoles" parameterType="role" resultMap="roleResultMap">
    select role_no,role_name,note from t_role
    where 1=1
    <choose>
        <when test="roleNo != null and roleNo !='' ">
            AND role_no = #{roleNo}
        </when>
        <when test="roleName != null and roleName !='' ">
            AND role_name like concat('%', #{roleName},'')
        </when>
        <otherwise>
            AND note is not null
        </otherwise>
    </choose>
</select>

三.trim,where set 元素

如果不知道where的条件十分存在,需要写 where 1=1,也可以写成<where></where>。

<select id="findOne" resultType="User">
    select*
     from user
     <where>
 			 id = #{id}
     </where>
</select>

使用trim去掉and ,or等语法。

<select id="findOne" resultType="User">
    select *
    from user
    <trim prefix="where" prefixOverrides="and">
 		and id = #{id}
    </trim>
</select>

set用来只发送想要更新的字段,不用像hibernate一样全部发送造成冗余。set遇到都和可以自动去掉。

<update id="setsql">
    update user
    <set>
        <if tes="roleName"!=null and roleName !=''">
          roleName=#{roleName} ,
        </if>
        <if tes="age"!=null and age !=''">
          age=#{age} 
        </if>
    </set>
    where id=131
</update>

四.foreache元素

foreach元素是一个循环语句,他的作用是遍历集合,支持数组,list,set接口的集合,对此提供遍历功能。往往用于in关键字。

  • collection 配置的roleNoList是传递进来的参数名称,可以是一个数组,list,set等集合。
  • item配置的是循环当中的元素
  • index配置的是当前元素在集合的位置下标
  • open和close配置的是以什么符号将这些集合元素包装起来。
  • separator是各个元素的间隔符
<select id="fubdUserBySex" resultType="user">
    slect * from t_role where role_no in 
        <foreach item="roleNo" index="index" collection="roleNoList" open="(" separator="," close="0">
        #{roleNo}
        </foreach>
</select>

五.用test的属性判断字符串

test用来判断真假,大部分用来判断空和非空,有时候需要判断字符串,数字,枚举等。

<select id="getRoleTest" parameterType="string" resultMap="roleResultMap">
    select role_no,role_name,note from t_role
    <if test=type='y'.toString>
        where 1=1
    </if>
</select>

六.bind元素

MySQL模糊查询,使用%和参数,但是Oracle没有,当使用bind就可以不适用数据库语言。

<select id ="findRole" parameterType="string" resultType="RoleBean">
    <bind name="pattern" value="'%' + _parameter +'%'"/>
    select * 
    from t_role
    where role_name like #{pattern}
</select>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值