Mybatis个人学习笔记(五)——动态sql语句

 根据条件查询(name或者age条件可能只有一个存在),给出了两种写法:

用到了if和where标签

<!-- 根据条件查询,不用where标签
<select id="findUserByCondition" resultMap="userMap" parameterType="user">
    select * from user where 1=1
    <if test="name != null">
                and name = #{name}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
</select>-->
    <!--使用where标签,#{}里面是传入的实体类的属性名,不能随意写-->
    <select id="findUserByCondition" resultType="com.mbtest.domain.User" parameterType="com.mbtest.domain.User">
        select * from userinfo
        <where>
            <if test="name != null">
                and name = #{name}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
        </where>
    </select>

  

 根据id集合(含有多个id)查询多行数据,用到了foreach标签:

属性: collection:id 集合,值为QueryVo类的属性名

           open:开始 ,值为  "and id in ("

           close:结束  ,  值为    ")"

           item:遍历的每一项,值为代号随便写,但下方#{}内的值要与之保持一致

          separator:分隔号,逗号

  <!-- 了解的内容:抽取重复的sql语句-->
    <sql id="defaultUser">
        select * from userinfo
    </sql>

    <!-- 根据queryvo中的Id集合实现查询用户列表 -->
    <select id="findUserInIds" resultType="com.mbtest.domain.User" parameterType="com.mbtest.domain.QueryVo">
        <include refid="defaultUser"></include>
        <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标签把该语句抽取出来,并通过include标签对其进行使用

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值