一,where、if标签
- where 标签:可以自动判断是否要删除语句块中的 and 关键字(若where与and相连接则删除)
- if 标签:可以自动根据表达式的结果来决定是否将对应的语句句添加到 SQL 中
<select id="findByAccount" parameterType="com.lin.entity.Account" resultType="com.lin.entity.Account">
select * from account
<where>
<if test="id!=0">
id=#{id}
</if>
<if test="username!=null">
and username=#{username}
</if>
<if test="password!=null">
and password=#{password}
</if>
<if test="age!=0">
and age=#{age}
</if>
</where>
</select>
二、choose 、when
- 若第一个when满足条件则不执行下面的when
- 若没有一个when满足条件则执行otherwise
<select id="findByAccount" parameterType="com.lin.entity.Account" resultType="com.lin.entity.Account">
select * from account
<where>
<choose>
<when test="id!=0">
id = #{id}
</when>
<when test="username!=null">
username = #{username}
</when>
<when test="password!=null">
password = #{password}
</when>
<when test="age!=0">
age = #{age}
</when>
<otherwise>
id=5
</otherwise>
</choose>
</where>
三、trim
prefix:在最前加入
suffix:在最后加入
prefixOverrides:去掉前面第一个
suffixOverrides:去掉后面最后一个
<!-- 等同于where -->
<trim prefix="where" prefixOverrides="and">
<!-- update语句可使用 -->
<trim prefix="set" suffixOverrides=",">
四、set
逗号会自动处理
<update id="update" parameterType="com.lin.entity.Account">
update account
<set>
<if test="username!=null">
username=#{username},
</if>
<if test="password!=null">
password=#{password},
</if>
<if test="age!=0">
age=#{age},
</if>
</set>
where id=#{id}
</update>
五、foreach标签
foreach 标签可以迭代生成一系列值,这个标签主要用于 SQL 的 in 语句。
select * from account where id in (1,2,3)
<select id="findByIds" parameterType="com.lin.entity.Account"
resultType="com.lin.entity.Account">
select * from account
<where>
<foreach collection="ids" open="id in (" close=")" item="id"
separator=",">
#{id}
</foreach>
</where>
</select>