什么是动态sql
动态sql是指sql并不事先确定好,而是在运行期动态生成。动态sql的出现,这不仅能令sql语句变得更加灵活,还能更近一步地优化sql语句的执行效率。
if
if的作用是当test中的条件满足时,将指定地sql语句添加入目标sql语句中。
下面是一个简单的示例。
<select id="queryBook" resultMap="BookResult">
SELECT b.bid,b.btitle,a.apseudonym,p.pname
FROM book_base_inf b
LEFT JOIN author_base_inf a ON b.aid=a.aid
LEFT JOIN publisher_base_inf p ON b.pid=p.pid
WHERE 1=1
<if test="title!= null">AND b.btitle LIKE #{title}</if>
<if test="author!= null">AND a.apseudonym LIKE #{author}</if>
<if test="publisher!= null">AND p.pname LIKE #{publisher}</if>
</select>
choose
chooes的作用与if的作用不同。chooes将第一个满足test中的条件的sql语句添加到目标sql语句中。
下面是一个简单的示例。
<select id="queryBook"
resultMap="BookResult">
SELECT b.bid,b.btitle,a.apseudonym,p.pname
FROM book_base_inf b
LEFT JOIN author_base_inf a ON b.aid=a.aid
LEFT JOIN publisher_base_inf p ON b.pid=p.pid
WHERE 1=1
<choose>
<when test="title!= null">AND b.btitle LIKE #{title}</when>
<when test="author!= null">AND a.apseudonym LIKE #{author}</when>
<when test="publisher!= null">AND p.pname LIKE #{publisher}</when>
<otherwise>AND 1=2</otherwise>
</choose>
</select>
trim
trim在java中的作用是去除首尾空白格。在mybatis中,trim有 了更加强大的功能。
下面是trim的使用模板。
<trim prefix="A" prefixOverrides="B">
...
</trim>
在这个示例中trim的作用是去除中间sql语句在首部的B,并且用A将其覆盖。
当A=“WHERE”,B="AND |OR "时,其等价于< where>
foreach
foreach的作用是迭代器。当传入的参数为集合时,foreach能迭代集合。
下面是一个简单的示例。
<select id="queryBook" resultMap="BookResult">
SELECT b.bid,b.btitle,a.apseudonym,p.pname
FROM book_base_inf b
LEFT JOIN author_base_inf a ON b.aid=a.aid
LEFT JOIN publisher_base_inf p ON b.pid=p.pid
<trim prefix="WHERE " prefixOverrides="AND |OR ">
<foreach item="book" index="index" collection="list">
<if test="book.title!= null">AND b.btitle LIKE #{book.title}</if>
<if test="book.author!= null">AND a.apseudonym LIKE #{book.author}</if>
<if test="book.publisher!= null">AND p.pname LIKE #{book.publisher}</if>
</foreach>
</trim>
</select>
在上面的示例中,依次迭代类型为list的集合,并且将当前的元素赋值给变量book。