SQL statements that change with user input or changes in external conditions are called dynamic SQL .
mybatisThe dynamic queries in are all composed of multiple tags
2. <if>, <where>and<set>
<if>: Used to determine whether the condition is established. Use testattributes for conditional judgment, and if the condition is true, then splicing SQL .
example:
<if test="name != null">
name like concat('%',#{name},'%')
</if>
Example:
<select id="list" resultType="com.itheima.pojo.Emp">
select *
from emp where
<if test="name!=null">
name like concat('%', #{name}, '%')
</if>
<if test="gender!=null">
and gender = #{gender}
</if>
<if test="begin!=null and end!=null">
and entrydate between #{begin} and #{end}
</if>
order by update_time desc
</select>
However, the above code has a shortcoming, that is, keywords such as where, andand can not be dynamically generated , which will cause grammatical errorsor
<where>: The where element will only insert the where clause when the child element has content . ANDAnd the or at the beginning of the clause will be automatically removed OR.
Improve:
select *
from emp
<where>
<!-- where的作用:1.动态的生成where 2.自动判断是否需要and , or等关键字 -->
<if test="name!=null">
name like concat('%', #{name}, '%')
</if>
<if test="gender!=null">
and gender = #{gender}
</if>
<if test="begin!=null and end!=null">
and entrydate between #{begin} and #{end}
</if>
</where>
order by update_time desc
</select>
<set>Replaces keywords and strips commas (used in statements) setbetween multiple assignments .update
//批量删除
public void deleteBylds(List<Integer> ids);
XML mapping file
<!--批量删除员工的操作 (18,19, 20)-->
<!--
collection :遍历的集合,与mapper中的集合名保持一致即可
item:遍历出来的元素,名称任取
separator:分隔符
open:遍历开始前拼接的SQ工片段
close:遍历结束局拼接的SQL片段
-->
<delete id="deleteByIds">
delete from emp where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
4.<sql>,<include>
<sql><include>These two tags solve the problem of code reusability, similar to the definition and call of methods
Original select statement (comparison)
<select id="list" resultType="com.itheima.pojo.Emp">
select id,username, password,name, gender,image,job,entrydate,dept_id,create_time,update_time
from emp
<where>
<if test="name!=null">
name like concat('%', #{name}, '%')
</if>
<if test="gender!=null">
and gender = #{gender}
</if>
<if test="begin!=null and end!=null">
and entrydate between #{begin} and #{end}
</if>
</where>
order by update_time desc
</select>
<sql>Extract a large number of multiplexed SQL statements
<select id="list" resultType="com.itheima.pojo.Emp">
<include refid="commonSelect"/>
<where>
<if test="name!=null">
name like concat('%', #{name}, '%')
</if>
<if test="gender!=null">
and gender = #{gender}
</if>
<if test="begin!=null and end!=null">
and entrydate between #{begin} and #{end}
</if>
</where>
order by update_time desc
</select>