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>