Day15JavaWeb【Mybatis二】动态标签***

动态标签介绍 ****

  • (1)动态标签是什么?
    由于mybatis将sql与java代码分离(sql写在xml中)
    if标签,where标签 forEach标签
  • (2)动态标签有什么用?
    用来根据数据的不同来生成对应的sql
  • (3)应用场景
    高级搜索功能
    搜索有多个条件,不是每个条件输入框都有值 ,此时需根据值来生成where条件

动态sql-if标签与where标签

  • (1)if标签
    》 if标签:可以判断传入的参数是否为空,如果不为空则拼接sql
  • (2)where标签
    》1 where标签:添加了where标签
    1:不用在初始sql后边写where 1=1
    2: 不用在第一个拼接的sql前写and,但是你也可以手动写and
  <select id="queryUserBySexAndName"  parameterType="User" resultType="User">
      select * from user
     <where>
          <if test="username != '' and username !=null ">
              and username like '${username}%'
          </if>
          <if test="sex != '' and sex != null">
              and sex = #{sex}
          </if>

         <if test="address != '' and address != null">
             and address = #{address}
         </if>
     </where>

  </select>

在接口写编写

   //根据性别或者名字进行查找
    List<User> findByUser(User user);

动态sql-foreach标签

  • (1)foreach标签
    向sql传递数组或List,mybatis使用foreach解析
  • (2)如何使用
    collection:表示方法传入的集合对象的名字 collection=“xxx”
    item:遍历集合时,会将集合中的元素赋值给item
    open表示你要拼接的sql以什么开始
    close:表示你拼接的sql以什么结束
    separator:表示拼接的分隔符
    接口中的变量名不能被标签识别,必须在参数的前边加注解@Param("xxx")
 <!--根据多个id来查找用户
      select * from user where id in(1,3,5)
      +++++++++
      select * from user where 1=1 and id in(1,3,5)

      collection:表示方法传入的集合对象的名字
      item:遍历集合时,会将集合中的元素赋值给item
      open表示你要拼接的sql以什么开始
      close:表示你拼接的sql以什么结束
      separator:表示拼接的分隔符

    -->
    <select id="queryUsersByIds" resultType="User">
        select * from user
        <where>
            <foreach collection="ids" item="id" open="and id in(" close=")"  separator=",">
                #{id}
            </foreach>
        </where>
    </select>


接口中实现

//根据多个ID来查找用户
//这里定义的变量,在UserDao中是不识别的,要想识别,必须在参数的前边加注解@Param("ids")
    List<User> queryUsersByIds(@Param("ids") List<Integer> ids);
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

翁老师的教学团队

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值