Mybatis(七)之SQL关系映射文件详解(二)

本文深入解析Mybatis中动态SQL的使用,涵盖if标签用于条件判断,where确保生成优雅的SQL语句,foreach进行遍历操作,以及如何运用sql片段提高代码复用。
摘要由CSDN通过智能技术生成

动态SQL

1.if

<!-- 演示动态sql-if标签的使用情景 -->
	<select id="getUserByWhere" parameterType="user" resultType="com.itheima.mybatis.pojo.User">
		SELECT * FROM USER where 1 = 1
		
		<!-- if标签的使用 -->
		<if test="id != null">
			and id = #{id}
        </if>
		<if test="username != null and username != ''">
			and username LIKE '%${username}%'
		</if>
		
	</select>
<!--
如果id不为null,username不为空和null,sql如下 
SELECT * FROM USER WHERE username LIKE '%${username}%' and id = #{id} 
-->

2.where

<select id="getUserByif" parameterType="com.lin.pojo.User" resultType="com.lin.pojo.User">
		selec * from user 
		<where><!-- where会自动加上where同处理多余的and -->
		<if test="username!=null and username!=''"> and username like'%${username}%'</if>
		<if test="sex!=null and sex!=''"> and sex =#{sex}</if>
		</where>
	</select>

3.foreach

<!-- 测试foreach标签 -->
	<select id="getUserByForeach" parameterType="com.lin.pojo.UserBuffered" resultType="com.lin.pojo.User">
	select * from user 
	<where> 
	<foreach collection="ids" open="id in (" item="id" separator="," close=")">
		<!--     foreach循环标签 
				 collection:要遍历的集合,来源入参 (ids是list类型)
				 open:循环开始前的sql 
				 separator:分隔符 
				 close:循环结束拼接的sql
		-->
	#{id}
	</foreach>
	</where> 
	</select>
	<!--等效于sql语句:select * from user where id in (1,2,3)-->

4.sql片段

1. 	定义
<!-- sql片段 定义,id:片段唯一标识 -->
	<sql id="user_column">
		id,username
	</sql>

2. 	使用
       SELECT
		<!-- sql片段的使用:include:引入sql片段,refid引入片段id -->
		<include refid="user_column" />
		FROM USER
	

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值