一、动态SQL
MyBatis提供的对SQL语句动态组装的功能,解决了根据需求去手动拼装SQL的麻烦工作。动态SQL是MyBatis的强大特性之一,MyBatis3采用了功能强大的基于OGNL的表达式来完成动态SQL.
主要元素有
二、if元素、
多条件组合查询
<select id="findCustomerByNameAndJobs" parameterType="com.itheima.po.Customer"
resultType="com.itheima.po.Customer">
select * from t_customer where 1=1
<if test="username !=null and username !=''">
and username like concat('%',#{username},'%')
</if>
<if test="jobs !=null and jobs !=''">
and jobs= #{jobs}
</if>
</select>
三、choose及其子元素
类似switch…case…default的使用
<!--<choose>(<when>、<otherwise>)元素使用 -->
<select id="findCustomerByNameOrJobs" parameterType="com.itheima.po.Customer"
resultType="com.itheima.po.Customer">
select * from t_customer where 1=1
<choose>
<when test="username !=null and username !=''">
and username like concat('%',#{username}, '%')
</when>
<when test="jobs !=null and jobs !=''">
and jobs= #{jobs}
</when>
<otherwise>
and phone is not null
</otherwise>
</choose>
</select>
四、set元素,where元素以及trim元素
4.1 set
set元素用于提高执行效率,只更新一条数据中需要更新的字段。
set和if元素组合使用时,要保证传入的更新字段不能都为空。
<!-- <set>元素 -->
<update id="updateCustomer" parameterType="com.itheima.po.Customer">
update t_customer
<set>
<if test="username !=null and username !=''">
username=#{username},
</if>
<if test="jobs !=null and jobs !=''">
jobs=#{jobs},
</if>
<if test="phone !=null and phone !=''">
phone=#{phone},
</if>
</set>
where id=#{id}
</update>
4.2 where 和trim
两者的作用差不多,都是为了保证拼接后SQL语句语法正确。
<!-- <trim>元素 -->
<select id="findCustomerByNameAndJobs" parameterType="com.itheima.po.Customer"
resultType="com.itheima.po.Customer">
select * from t_customer
<trim prefix="where" prefixOverrides="and">
<if test="username !=null and username !=''">
and username like concat('%',#{username}, '%')
</if>
<if test="jobs !=null and jobs !=''">
and jobs= #{jobs}
</if>
</trim>
</select>
五、 foreach元素,bind元素
foreach元素用于遍历出想要的结果集。
open和close配置的是以什么符号将这些集合元素包装起来。
separator配置的是各个元素的间隔符。
使用foreach最关键也是最容易出错的是collection属性。
<!--<foreach>元素使用 -->
<select id="findCustomerByIds" parameterType="List"
resultType="com.itheima.po.Customer">
select * from t_customer where id in
<foreach item="id" index="index" collection="list" open="("
separator="," close=")">
#{id}
</foreach>
</select>
bind元素:避免项目移植的麻烦
<!--<bind>元素的使用:根据客户名模糊查询客户信息 -->
<select id="findCustomerByName" parameterType="com.itheima.po.Customer"
resultType="com.itheima.po.Customer">
<!--_parameter.getUsername()也可直接写成传入的字段属性名,即username -->
<bind name="pattern_username" value="'%'+_parameter.getUsername()+'%'" />
select * from t_customer
where
username like #{pattern_username}
</select>