MyBatis 中的动态 sql

xxxMapper 中的 select 标签中的 if 和 where 标签

<!-- 使用动态 sql 进行用户信息综合查询 -->
<select id="getListByConditions" resultType="user" parameterType="user">
    select * from user
    <!-- where 标签可以自动添加 where 和去除条件中的第一个 and -->
    <where>
        <if test="username != null">
            and username like '%${username}%'
        </if>
        <if test="sex != null">
            and sex=#{sex}
        </if>
    </where>
</select>

sql 片段

需求:将上边实现的动态 sql 判断代码块抽取出来,组成一个 sql 片段,其他的 statement 中就可以引用该 sql 片段。

1、定义 sql 片段( xxxMapper的mapper标签中定义 ):

<!-- 定义 sql 片段
    id: sql 片段的唯一标识
    经验:1、要基于单表来定义sql片段,这样在进行多表查询时引用才方便,可重用性才高
        2、在 sql 片段中不要包括where,where写在具体的查询的select标签中 -->
<sql id="query_user_where">
    <if test="username != null">
        and username like '%${username}%'
    </if>
    <if test="sex != null">
        and sex=#{sex}
    </if>
</sql>

2、引用 sql 片段:

<select id="getListByConditions" resultType="user" parameterType="user">
    select * from user
    <where>
        <!-- 引用 sql 片段,可以引用多个
                refid:所引用的 sql 片段的 id,如果 refid 指定的 sql 片段 不在本 xxxMapper.xml 文件中,需要在前面加 namespace的值 -->
        <include refid="query_user_where"></include>
    </where>
</select>

xxxMapper 中的 select 标签中的 foreach 标签

遍历集合:

<select id="" parameterType="user" resultType="">
    <!-- 使用 foreach 遍历传入的 user 对象中的的id 的 list集合
            实现这个sql的拼接:and (id=1 or id=10 or id=16) -->
    <!-- collection:指定输入对象中的集合名称
        item:每次遍历生成的对象
        open:开始遍历时拼接的串
        close:结束遍历时拼接的串
        separator:遍历的两个对象之间需要拼接的串 -->
    <foreach collection="ids" item="user_id" open="abd (" close=")" separator="or">
        <!-- 每个遍历需要拼接的串 -->
        id=#{user_id}
    </foreach>
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值