mapper.xml
<!--
set作用: 会自动增加set关键字,并且会去除最后一个逗号
只可以使用修改
-->
<update id="update">
update flower
<set>
<if test="name!=null and name!=''">
name =#{name},
</if>
<if test="production!=null and production!=''">
production=#{production},
</if>
id =#{id}
</set>
where
id =#{id}
</update>
<!--
prefix:增加前缀
prefixOverrides:去除前缀
suffix:增加后缀
suffixOverrides:去除后缀
-->
<update id="update2">
update flower
<trim prefix="set" suffixOverrides=",">
<if test="name!=null and name!=''">
name =#{name},
</if>
<if test="production!=null and production!=''">
production=#{production},
</if>
</trim>
where
id =#{id}
</update>
<!--
collection: list/array
open:开始
close:关闭
separator:分割
item:赋值给指定属性
-->
<select id="selectMore5" resultType="flower">
SELECT <include refid="sq1"></include> FROM flower WHERE id in
<foreach collection="list" open="(" separator="," close=")" item="ii">
#{ii}
</foreach>
</select>
<select id="selectMore6" resultType="flower">
SELECT <include refid="sq1"></include> from flower
<where>
<if test="param1!=null and param1!=''">
<!--模糊查询拼接-->
<bind name="pa" value="'%'+param1+'%'"></bind>
name like #{pa}
</if>
<if test="param2!=null and param2!=''">
and production =#{param2}
</if>
</where>
</select>
<!--公共sql片段-->
<sql id="sq1">
id,name,price,production
</sql>
MyBatis中动态拼接标签小结:
if :类似于if()只要满足条件就可以拼接
where:增加where关键字 去除第一个and --查询
choose:类似if(){}else if(){},只会进入符合条件的第一个
set:会自动增加set关键字 ,去除最后一个逗号--修改
trim:可以增加(去除)前缀或者后缀
foreach:进行集合或者数组的遍历
bind:使用模糊查询进行字符的拼接
sql:提取公共sql片段
include:引入sql片段