我们根据实体类的不同取值,使用不同的 sql 语句来进行查询,所以需要动态的合成 sql 语句。
一、关键字标签
<trim>: 格式化标签。
<where>: 代表 sql 条件关键字 where。
<set>: 代表 sql update 更新字段关键字 set。
<!--动态Sql: trim 标签-->
<select id="dynamicSqlTrim" resultType="com.lks.domain.User">
select * from users
<trim prefix="where" suffix="order by age" prefixOverrides="and | or"
suffixOverrides=",">
<if test="name != null and name != ''">
AND name = #{name}
</if>
<if test="county != null and county != ''">
AND county = #{county}
</if>
</trim>
</select>
trim 标签的属性含义如下:
标签用于格式化,它的属性:
- prefix:前缀。
- suffix:后缀。
- prefixOverrides:去掉第一个 and 或者是 or。
- suffixOverrides:去掉最后一个逗号,也可以是其他的标记。
二、条件查询
<if> 和 <choose>、<when>、<otherwise>(类似 java switch)。
<select id=