mybatis基于XML配置的动态SQL语句

mybatis动态SQL语句

mappers配置文件中的几个标签:
	<if>
	<where>
	<foreach>
	<sql>

If标签

  • 1 . 作用:
当if标签的test成立时,就把if标签中的内容,拼接到上边的sql语句的后边
  • 2 . 案例:
<!-- 此处配置了别名,因此参数类型以及返回值类型可以使用简略写法-->
<select id="findUserByIf" resultType="user" parameterType="user">
	select * from user where 1=1
	<!-- 判断姓名是否为null或空字符串,为空则不进行SQL语句拼接-->
	<if test="username != null and username != '' ">
		and username = #{username}
	</if>
	<!-- 判断性别是否为空,为空则不进行SQL语句拼接-->
	<if test="sex != null">
		and sex = #{sex}
	</if>
</select>

where标签

  • 1 . 作用:
用于"多条件不确定"查询时,确定在拼接sql语句时,是否把"and"关键字给替换为"where"
使用while标签时,第一个if标签中的sql语句,可以省略and关键字
  • 2 . 案例:
<!-- 此处配置了别名,因此参数类型以及返回值类型可以使用简略写法-->
<select id="findUserByWhere" resultType="user" parameterType="user">
	select * from user
	<where>
		<if test="username != null">
			and username = #{username}
		</if>
		<if test="sex != null">
			and sex = #{sex}
		</if>
	</where>
</select>

foreach标签

  • 1 . 作用:
当需要遍历"传入参数",并拼接sql语句时. //特别是类似于 id in (1,5,8)  之类的内容
  • 2 . 案例:
<!-- 此处配置了别名,因此参数类型以及返回值类型可以使用简略写法-->
<select id="findUserInIds" resultType="user" parameterType="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>
  • 3 . 解析(foreach标签)
collection	:表示被遍历的集合
item		:集合中的每个元素
separator	:拼接的每个元素之间的分割
open		:被拼接的语句的开始
#{uid}		:被循环拼接的东西
close		:被拼接的语句的结束
  • 4 . 注意:
4.1:如果要遍历的是对象中的属性,则 collection="属性名"
4.2:如果要遍历的是传入参数本身(也就是说,传递的参数本身就是一个集合或数组)
		如果是List集合,则 collection="list"
		如果是数组,则 collection="array"
		如果是Set集合,则:
			第1步: 在接口的方法上,添加@Param("set")
				   //List<User> findUserBySet(@Param("set") Set<Integer> ids);
			第2步: collection="set"
4.3:传入参数仅限一个.

sql标签(sql语句片段)

Sql 中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的
  • 定义代码片段
<!-- 抽取重复的语句代码片段 -->
<sql id="defaultSql">
    select * from user
</sql>
  • 引用代码片段
<!-- 配置查询所有操作 -->
<select id="findAll" resultType="user">
<include refid="defaultSql"></include>
</select>

<!-- 根据 id 查询 -->
<select id="findById" resultType="UsEr" parameterType="int">
    <include refid="defaultSql"></include>
    where id = #{uid}
</select>

猜你喜欢

转载自blog.csdn.net/weixin_43343131/article/details/84762486