MyBatis 动态SQL技术

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能。

sql 标签

<sql id="empColumns">
eid,ename,age,sex,did
</sql>
select <include refid="empColumns"></include> from t_emp

可以记录一段公共sql片段,在使用的地方通过include标签进行引入

if 标签

<select id="getEmpListByMoreTJ" resultType="Emp">
	select * from t_emp where 1=1
	<if test="ename != '' and ename != null">
	and ename = #{ename}
	</if>
	<if test="age != '' and age != null">
	and age = #{age}
	</if>
	<if test="sex != '' and sex != null">
	and sex = #{sex}
	</if>
</select>

if标签可以通过test属性的表达式进行判断,若表达式结果为true,则执行标签中的内容。

where 标签

<select id="getEmpListByMoreTJ2" resultType="Emp">
	select * from t_emp
	<where>
		<if test="ename != '' and ename != null">
		and ename = #{ename}
		</if>
		<if test="age != '' and age != null">
		and age = #{age}
		</if>
		<if test="sex != '' and sex != null">
		and sex = #{sex}
		</if>
	</where>
</select>

where 一般和 if 结合使用。where会去掉条件开头多余的and

trim 标签

<select id="getEmpListByMoreTJ" resultType="Emp">
	select * from t_emp
	<trim prefix="where" suffixOverrides="and">
		<if test="ename != '' and ename != null">
		ename = #{ename} and
		</if>
		<if test="age != '' and age != null">
		age = #{age} and
		</if>
		<if test="sex != '' and sex != null">
		sex = #{sex}
		</if>
	</trim>
</select>

trim用于去掉或添加标签中的内容

常用属性:
prefix:在trim标签中的内容的前面添加某些内容
prefixOverrides:在trim标签中的内容的前面去掉某些内容
suffix:在trim标签中的内容的后面添加某些内容
suffixOverrides:在trim标签中的内容的后面去掉某些内容

foreach 标签

foreach 用于批量操作数据库。foreach标签的内容存放用于循环的sql操作。
比如在批量删除和添加时,需要用到foreach。

  • 批量添加:
<!--void insertManyEmp(@Param("emps") List<Emp> emps);-->
<insert id="insertManyEmp">
    insert into t_emp values
    <foreach collection="emps" item="emp" separator=",">
        (null,#{emp.empName},#{emp.age},#{emp.gender},null)
    </foreach>
</insert>
  • 批量删除:
<!--void deleteManyEmp(@Param("empIds") Integer[] empIds);-->
<delete id="deleteManyEmp">
    delete from t_emp where emp_id in (
    <foreach collection="empIds" item="empId" separator=",">
        #{empId}
    </foreach>)
</delete>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值