MyBatis的动态SQL

映射文件的SQL深入

动态SQL语句

可根据条件判断动态生成SQL


if标签

语句格式

<if test=" 条件判断 ">
	SQL语句
</if>

test属性为: 判断的条件, 当条件为true时, 添加标签中的语句

示例(判断user的属性值 是否为空)

<!-- 根据条件查询 -->
<select id="findUserByCondition" parameterType="user" resultType="user">
    SELECT * FROM user WHERE 1=1
    <if test="username != null">
        AND username=#{username}
    </if>
    <if test="sex != null">
        AND sex=#{sex}
    </if>
</select>

!注意: 判断当中的 ‘与’ 必须使用 AND


where标签

不需要在SQL语句后加 WHERE 条件

语句格式

<where>
    SQL语句
</where>

示例

<select id="findUserByCondition" parameterType="user" resultType="user">
    SELECT * FROM user
    <where>
        <if test="username != null">
            AND username=#{username}
        </if>
        <if test="sex != null">
            AND sex=#{sex}
        </if>
    </where>
</select>

foreach标签

语句格式

<foreach collection="集合" open="语句的开始" close="语句的结束" item="元素变量名" separator="分割符">
    #{元素变量名}
</foreach>

collection属性为: 需要遍历的集合

open属性为: SQL 语句的开始

close属性为: SQL 语句的结束

item属性为: 集合元素的变量名 – 相当于 for(int i = 0; i < 10; i++){...} 里的i变量

separator属性为: 元素间以什么字符分割

使用#{变量名} 可取出元素的值

以上的真实SQL语句为: 语句的开始 元素1 分割符 元素2 分割符 元素3 ... 语句结束

示例(更具ID的集合 查询用户) SQL语句为 SELECT * FROM user WHERE id in (元素1, 元素2, 元素3, ...);

<!-- 根据QueryVo中的Id集合查询用户 -->
<select id="findUserByIds" parameterType="QueryVo" resultType="User">
    SELECT * FROM user
    <where>
        <if test="ids != null and ids.size() > 0">
            <foreach collection="ids" open="and id in (" close=")" item="uid" separator=",">
                #{uid}
            </foreach>
        </if>
    </where>
</select>

sql标签

可以抽取重复的SQL语句, 节省代码量

语句格式<sql>

<sql id="引用id">
    SQL语句
</sql>

id属性为: SQL语句的引用名

引用格式<include>

<select id="***" resultType="***">
    <include refid="引用id"/>
</select>

refid属性为: 需要引用的SQL语句 引用名

示例

<sql id="select">
    SELECT * FROM user;
</sql>

<select id="findAll" resultType="user">
    <include refid="select"/>
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值