动态标签介绍 ****

  • (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);