MyBatis动态SQL学习

本文详细介绍了MyBatis中的动态SQL技术,包括if、where、foreach、trim等标签的使用方法,以及${}

If where 标签

动态sql可以提升代码的重用性,即可以使用较少的代码实现不同的功能
if标签的主要参数为 test test内写入判断条件
例:查询sql:

<select id="listHouse" resultMap="listHouseByStep" parameterType="hashmap">
        SELECT HOUSEID,HOUSEPOSITION,COMMUNITYID,HOUSEAREA,SALEAREA,HTID,HOUSESTRUCTURE,SALETYPE,HSID,DONGID FROM HOUSEDATA
    </select>

现在sql只具备查询功能

使用if语句动态sql后:

    <select id="listHouse" resultMap="listHouseByStep" parameterType="hashmap">
        SELECT HOUSEID,HOUSEPOSITION,COMMUNITYID,HOUSEAREA,SALEAREA,HTID,HOUSESTRUCTURE,SALETYPE,HSID,DONGID FROM HOUSEDATA
        <if test="_parameter != null">
        	<where>
	            <trim suffixOverrides="and" prefixOverrides="or" >
	                    <if test="housetid !=null and housetid!=0 ">
	                         AND HTID = #{housetid} and
	                    </if>
	                    <if test="commid != null and commid != 0">
	                         COMMUNITYID = #{commid} and
	                    </if>
	                    <if test="dong != null and dong != 0">
	                       DONGID = #{dong} and
	                    </if>
	                    <if test="houseSid != null and houseSid != 0">
	                        HSID = #{houseSid} and
	                    </if>
	            </trim>
            </where>
          </if>
    </select>

使用if动态sql后就可以实现不同的查询功能,if标签添加不同的判断条件,实现对sql语句的动态改变
此处_parameter 为外部传入的参数,传入参数为hashmap时可以直接写键值来获取到对应的value值

foreach 标签

foreach标签可以遍历list或者array
foreach标签主要有以下参数:
collection: 数据类型,传入list集合时写list,传入数组时写array
item :循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details,在list和数组中是其中的对象,在map中是value。
index :在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
open :表示该语句以什么开始
close :表示该语句以什么结束
separator :表示元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
例:在我们查询时需要筛选出固定的一些数据

    <select id="listHouseByExport" resultMap="listHouseByStep">
        SELECT HOUSEID,HOUSEPOSITION,COMMUNITYID,HOUSEAREA,SALEAREA,HTID,HOUSESTRUCTURE,SALETYPE,HSID,DONGID FROM HOUSEDATA
        <where>
            <if test="array != null and array.length != 0">
                HOUSEID IN
                <foreach collection="array" item="houseid" close=")" open="(" separator="," >
                    #{houseid}
                </foreach>
            </if>
        </where>
    </select>

trim 语句

trim 是一个格式化标签,可以完成< set > 或者是 < where > 标记的功能。主要有4个参数:
① prefix:前缀
② prefixOverrides:移除前缀
③ suffix:后缀
④ suffixOverrides:移除后缀
例:

         <trim suffixOverrides="and" prefixOverrides="or" >
                 <if test="housetid !=null and housetid!=0 ">
                      AND HTID = #{housetid} and
                 </if>
                 <if test="commid != null and commid != 0">
                      COMMUNITYID = #{commid} and
                 </if>
                 <if test="dong != null and dong != 0">
                    DONGID = #{dong} and
                 </if>
                 <if test="houseSid != null and houseSid != 0">
                     HSID = #{houseSid} and
                 </if>
         </trim>

此处trim标签就是移除多余的前缀or和后缀 and,放置sql出错

${}和#{}

传参数 KaTeX parse error: Expected 'EOF', got '#' at position 5: {} 和#̲{}区别 Mybatis 的M…{}
我们经常使用的是#{},一般解说是因为这种方式可以防止SQL注入,简单的说#{}这种方式SQL语句是经过预编译的,它是把#{}中间的参数转义成字符串,举个例子:

select * from student where studentName = #{name} 

预编译后,会动态解析成一个参数标记符?:

select * from student where studentName = ?

而使用${}在动态解析时候,会传入参数字符串

select * from student where studentName = 'lyrics'

SQL 片段

此处引用大佬代码:跳转

有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。
比如:假如我们需要经常根据用户名和性别来进行联合查询,那么我们就把这个代码抽取出来,如下:

<!-- 定义 sql 片段 -->
<sql id="selectUserByUserNameAndSexSQL">
    <if test="username != null and username != ''">
        AND username = #{username}
    </if>
    <if test="sex != null and sex != ''">
        AND sex = #{sex}
    </if>
</sql>

调用sql

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    select * from user
    <trim prefix="where" prefixOverrides="and | or">
        <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
        <include refid="selectUserByUserNameAndSexSQL"></include>
        <!-- 在这里还可以引用其他的 sql 片段 -->
    </trim>
</select>

choose(when,otherwise) 语句

choose 主要是用于分支判断,类似于java中的switch case,只会满足所有分支中的一个

<select id="getEmpsByConditionChoose" resultType="com.atguigu.mybatis.beans.Employee">
		select id ,last_name, email,gender from tbl_employee
		<where>
			<choose>
				<when test="id!=null">
					id = #{id}
				</when>
				<when test="lastName!=null">
					last_name = #{lastName}
				</when>
				<when test="email!=null">
					email = #{email}
				</when>
				<otherwise>
					 gender = 'm'
				</otherwise>
			</choose>
		</where>
</select>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值