MyBatis入门【六】动态SQL

49 篇文章 5 订阅
37 篇文章 1 订阅

在MyBatis中,运用动态SQL可以进行动态的添加操作数据库的条件,使操作数据库更加灵活

代码示例

<!-- where可以自动去掉条件中的第一个and -->
<select id="findUserList" parameterType="UserQueryVo全路径/别名" resultMap="UserCustom全路径">
    SELECT * FROM USER
    <where>
        <if test="userCustom != null">
            <if test="userCustom.sex != null and userCustom.sex != ' ' ">
                and user.sex = #{userCustom.sex}
            </if>
            <if test="userCustom.username != null and userCustom.username != ' ' ">
                and user.username LIKE '%${userCustom.username}%'
            </if>
        </if>
    </where>
</select>

SQL片段

将动态SQL代码抽取出来形成SQL片段,其他statement就可以调用定义SQL片段,

id:SQL片段唯一标识

经验:

  • 1、基于单表来定义SQL片段,SQL片段可重用性高
  • 2、在SQL片段中不要包含where
<sql id="query_user_where">
    <if test="userCustom != null">
        <if test="userCustom.sex != null and userCustom.sex != ' ' ">
            and user.sex = #{userCustom.sex}
        </if>
        <if test="userCustom.username != null and userCustom.username != ' ' ">
            and user.username LIKE '%${userCustom.username}%'
        </if>
    </if>
</sql>

引用SQL片段

<select id="findUserList" parameterType="UserQueryVo全路径/别名" resultMap="UserCustom全路径">
    SELECT * FROM USER
    <where>
        <!-- 引用SQL片段 id,如果不在本mapper文件中,需要前边添加namespace -->
        <include refid="query_user_where"></include>
        <!-- 在这里还可引用其他SQL片段 -->
    </where>
</select>

foreach

向SQL中传递数组或List,mybatis使用foreach解析

1、select * from user where id=1 or id=10 or id=123

包装类的定义

public class UserQueryVo{
    //传入多个id
    private List<Integer> ids;
    //在此处应生成setget
}

mapper.xml文件中SQL片段:

<!-- 使用foreach遍历ids
    collection:指定输入对象中集合属性
    item:每个遍历生成对象串
    open:开始遍历时拼接的串
    close:结束遍历时拼接的串
    separator:遍历的两个对象中需要拼接的串
-->
<foreach collection="ids" item="user_id" open="AND (" close=")" separator="or">
    <!-- 每个遍历需要拼接的串-->
    id=#{user_id}
</foreach>

效果串: AND (id=1 or id=10 or id=123)

2、select * from user where id in (1,10,123)

<foreach collection="ids" item="user_id" open="AND id IN (" close=")" separator=",">
    <!--每个遍历需要拼接的串-->
    i#{user_id}
</foreach>

效果串: AND id IN(1 ,10, 23)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值