ORM框架之Mybatis(三):动态SQL和批处理

看着标题感觉很高大上,实际上的确不算low。动态SQL是一些标签对动态拼接SQL操作的优化,使代码更加的优雅、简洁。再就是批处理,常用的就是foreach标签,但是还有另一种方式也是可以了解一下的,虽然在实际开发上不怎么用,但是知道还是必须滴,从功利来说,面试要是被问到可以用来做加分项,从心理上来说,同事间聊起来可以……。

if标签

if标签在开发过程用的最多,因为要做一些字段的非空等校验,保证SQL的正确性。看个例子:

<select id = "selectUser" parameterType="com.zdydoit.User" resultType="com.zdydoit.User">
    select id,user_name,age,phone,height,position_id,created_time,updated_time
    from t_user
    where 1=1
    <if test="userName != null and userName !=''">
        and user_name = #{userName}
    </if>
    <if test="phone != null and phone !=''">
        and phone = #{phone}
    </if>
    <if test="age != null">
    	and age = #{age}
    </if>
</select>

这个用法很简单,test属性就相当于java代码中if括号内的内容。有两个细节可以注意一下。

  • 第一点,在判断字符串的时候,是双重条件,同时判断null和空串,而数值、日期只要判断非空即可。
  • 另外还有一点就是这里的判断是遵循短路与的,test里面的and连接符就符合这个规则,当前一个条件判断false后,and后面的就不会再判断,这样在对象判断的时候就会避免出现空指针问题。

where标签

上面if标签的实例可以看的出来在where条件中代码是很不优雅的,有一个1=1,就是为了防止where后面紧接着的是and,导致代码报错。这里就用到where标签来优化。如下:

<select id = "selectUser" parameterType="com.zdydoit.User" resultType="com.zdydoit.User">
    select id,user_name,age,phone,height,position_id,created_time,updated_time
    from t_user
    <where>
        <if test="userName != null and userName !=''">
            and user_name = #{userName}
        </if>
        <if test="phone != null and phone !=''">
            and phone = #{phone}
        </if>
        <if test="age != null">
            and age = #{age}
        </if>
    </where>
</select>

这样的好处就是可以去除开头可能出现and或者or的问题,同时如果if条件都不满足,那么就不会有where条件内容。另外还有一个很大的好处,就是使代码得到了优化。你是不是也用过1=1,看完这一段是不是赶紧打开项目开始改代码啦。

set标签

set标签和where标签是类似的,只是使用的位置不同,set标签是用在update语句下。如下:

<update id="updateUser" paramterType="com.zdydoit.User">
    update t_user
    set
    	<if test="userName != null and userName != ''">
    		user_name = #{userName},
    	</if>
        <if test="phone != null and phone != ''">
    		phone = #{phone},
    	</if>
        <if test="positionId != null">
    		position_id = #{positionId},
    	</if>
    	id = #{id}
    where id = #{id}
</update>

这是优化前的代码,感觉是无懈可击,但是set里面的内容还是感觉有点别扭,多写了一个id=#{id},完全就是为了防止最后一个条件后面有逗号出现导致SQL报错而存在。和where里面加上1=1是同一个意思,where可以优化,set当然也可以。

优化后代码:

<update id="updateUser" paramterType="com.zdydoit.User">
    update t_user
    <set>
    	<if test="userName != null and userName != ''">
    		user_name = #{userName},
    	</if>
        <if test="phone != null and phone != ''">
    		phone = #{phone},
    	</if>
        <if test="positionId != null">
    		position_id = #{positionId},
    	</if>
    </set>
    where id = #{id}
</update>

是不是看着就很爽啦。这里set会自动去除掉结尾的逗号,保证SQL的正确性。

trim标签

trim标签适用的范围比较广,可以用来替代whereset标签,换句话说,whereset标签是优化后的trim标签。where是用在where条件的时候,set是用在update语句中,现在还差insert语句没有得到优化。

优化前的代码:

<insert id="insertUser" parameterType="com.zdydoit.User">
    insert into t_user
    (
    	<if test="userName != null and userName !=''">
            user_name,
    	</if>
        	<if test="phone != null and phone !=''">
            phone,
    	</if>
        	<if test="positionId != null">
            position_id,
    	</if>
    	created_time
    )
    values
    (
        <if test="userName != null and userName !=''">
            user_name,
    	</if>
        <if test="phone != null and phone !=''">
            phone,
    	</if>
        <if test="positionId != null">
            position_id,
    	</if>
    	NOW()
    )
</insert>

和之前的whereset同样的解决方案,加一个字段created_time,其实这里用created_time有点牵强,但是也要看建库的习惯。比如我建库的时候,习惯将created_time这个字段设置成CURRENT_TIMESTAMP,这样插入数据的时候就不用特意的去赋值,数据库会自动将当前时间填到这个字段中,有点跑偏了。继续回到优化上来,优化如下:

<insert id="insertUser" parameterType="com.zdydoit.User">
    insert into t_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
    	<if test="userName != null and userName !=''">
            user_name,
    	</if>
        	<if test="phone != null and phone !=''">
            phone,
    	</if>
        	<if test="positionId != null">
            position_id,
    	</if>
    </trim>
	<trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="userName != null and userName !=''">
            user_name,
    	</if>
        <if test="phone != null and phone !=''">
            phone,
    	</if>
        <if test="positionId != null">
            position_id,
    	</if>
    </trim>
</insert>

完美的对insert语句进行了优化。这里trim标签有下面四个属性:

  • prefix表示前缀内容;
  • suffix表示后缀内容;
  • prefixOverrides标签内内容开头需要覆盖的部分;
  • suffixOverrides标签内内容结尾需要覆盖的部分。

上面说了wheresettrim的优化版,那用trim肯定可以实现whereset的功能,看下面简化的代码:

<!-- 替换where -->
<trim prefix="where " prefixOverrides="and | or">
    <!-- 忽略内容 -->
</trim>
<!-- 替换set -->
<trim prefix="set " suffixOverrides=",">
    <!-- 忽略内容 -->
</trim>

虽然trim可以用来替代whereset,但是实际使用上还是用whereset更好,不需要设置属性值,直接用就好,简洁不易出错,而且辨识度很高,用在对应的位置一看就知道。

foreach标签

这个标签可用于批处理,也可用于一些条件的组合。用法如下:

<!-- in条件查询 -->
<select id = "selectByIds" parameterType="java.util.List">
    select id,user_name,phone,age,position_id
    from t_user
    <where>
    	<if test="userIds != null and userIds.size()>0">
            id in
        	<foreach collection="userIds" item="id" separator="," open="(" close=")">
                #{id}
            </foreach>
        </if>
    </where>
</select>
<!-- 批量插入 -->
<insert id = "batchInsert" parameterType="java.util.List">
    <if test="users != null and users.size()>0">
        insert into t_user
        (user_name,phone,age,position_id)
        values
        <foreach collection="users" item="user" separator="," open="(" close=")">
            #{userName},
            #{phone},
            #{age},
            #{positionId}
        </foreach>
    </if>
</insert>

第一种用的是in多条件查询,第二种用的是批量插入数据。其中的collection字段表示当前参数中的集合,item表示的是collection中遍历出来的元素,open表示遍历单条内容的开始符号,close表示遍历单条内容结束符号,separator表示的是每次循环结束后使用的分隔符。

批处理的另一种方式

上面说了可以使用foreach实现批处理,但是这里还有一种方式就是通过配置defaultExecutorType属性为BATCH来实现,配置位置是mybatis的mybatis-config.xml配置文件中的settings标签下(具体可以参考ORM框架之Mybatis:基础配置)。当配置后,一个事务中执行的多个SQL不会单独的自动提交,而是通过最后commit才会一次性提交所有SQL。

defaultExecutorType有三个可选值,分别是SIMPLEREUSEBATCH,默认的是SIMPLE没有特殊的说明,REUSE表示重用预处理语句,而BATCH表示重用语句和批量处理。但是实际上使用BATCH的场景并不多,为了项目中仅有的几个用的上批处理的业务,做一系列的批处理配置并不划算,另外一般的批处理foreach已经可以应付,无需配置BATCH

choose、when、otherwise组合标签

这三个标签是组合使用的,同时这些使用场景也不多,所以这里放到最后来写。

<select id = "selectUser" parameterType="java.lang.Integer">
    select id,user_name,phone,age,position_id
    from t_user
    <where>
        <choose>
            <when test="userName != null and userName !=''">
                user_name = #{userName}
            </when>
            <when test="phone != null and phone !=''">
            	phone = #{phone}
            </when>
            <otherwise>
            	1=1
            </otherwise>
        </choose>
    </where>
</select>

这三个标签是组合使用的,otherwise标签官方说明是必须存在的,但是实际使用中是可以不要的,需要看实际的需求和where条件的书写格式。

这连个标签一起使用类似于if…else if…else实现方式。如果其中有一个条件成立,其他判断条件内的内容就被略过。一般用于几个筛选条件,条件有一定的优先级。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿洞晓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值