动态sql
利用动态 SQL,可以彻底摆脱动态拼接 sql 的痛苦
●if
●choose (when, otherwise)
●trim (where, set)
●foreach
if + where 条件
<!--姓名、密码动态查询,为空就是全查询--><select id="find1" resultMap="usermap">select * from user where 1=1<if test="name!=null">and username = #{name}</if><if test="password!=null">and password = #{password}</if></select>
改进写法,使用 where 标签,会智能的给我们添加 where 关键字,并且能智能的帮我们去掉 and
<select id="find1" resultMap="usermap">select * from user<where><if test="name!=null">and username = #{name}</if><if test="password!=null">and password = #{password}</if></where></select>
if + set 条件
set 标签同样很智能,会帮我们智能的去掉最后的逗号
<!--传什么参数就修改什么字段--><update id="update">update user<set><if test="name!=null">username = #{name},</if><if test="age!=null">age = #{age},</if><if test="address!=null">address = #{address},</if><if test="password!=null">password = #{password},</if></set>where id = #{id}</update>
trim(基本上用不到了) ;
属性
●prefix:加前缀
●prefixOverrides:去掉前缀
●suffix:加后缀
●suffixOverrides:去掉后缀
<select id="find2" resultMap="usermap">select * from user<trim prefix="where" prefixOverrides="and"><if test="name!=null">and username = #{name}</if><if test="password!=null">and password = #{password}</if></trim></select>
<update id="update2">update user<trim prefix="set" suffixOverrides=","><if test="name!=null">username = #{name},</if><if test="age!=null">age = #{age},</if><if test="address!=null">address = #{address},</if><if test="password!=null">password = #{password},</if></trim>where id = #{id}</update>
