动态SQL
根据具体的参数条件,来对SQL语句进行动态拼接。
在以前的开发中,由于不确定查询参数是否存在,许多人会使用类似于where 1 = 1
来作为前缀,这样,就算要查询的参数为空,也能够正确执行查询,如果不加1 = 1
,则如果查询参数为空,SQL语句就会变成SELECT * FROM student where
,SQL语句不合法
mybatis里的动态标签:
-
if
<!-- 示例 --> <select id="find" resultType="student" parameterType="student"> SELECT * FROM student WHERE age >= 18 <if test="name != null and name != ''"> AND name like '%${name}%' </if> </select>
当满足test条件的时候, 才会将
<if>
标签内的SQL语句拼接上去 -
choose
<!-- choose 和 when , otherwise 是配套标签 类似于java中的switch,只会选中满足条件的一个 --> <select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <choose> <when test="title != null"> AND title like #{title} </when> <when test="author != null and author.name != null"> AND author_name like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose> </select>
这个类似于
switch
语句 -
trim
-
where
<where>
标签只会在至少有一个子元素返回了SQL语句时,才会向SQL语句中添加where
,如果where
之后以AND
或OR
开头,会自动将其删掉<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </where> </select>
<where>
标签还可以用<trim>
标签替代<trim prefix="WHERE" prefixOverrides="AND | OR"> ... </trim>
-
set
在至少有一个子元素返回了SQL语句时,才会向SQL语句中添加
SET
,并且如果SET
之后是以,
开头的话,会自动将其删掉<set>
标签相当于如下的<trim>
标签<trim prefix="SET" prefixOverrides=","> ... </trim>
-
可以通过<trim>
标签更加灵活的对SQL进行定制
-
foreach
用来做迭代拼接,通常与SQL语句中的
IN
查询条件结合使用,注意,当parameterType
为List
(链表)或者Array
(数组),后面在引用时,参数名必须为list或者array。如在foreach
标签中,collection
属性则为需要迭代的集合,由于入参是个List,所以参数名为list<select id="batchFind" resultType="student" parameterType="list"> SELECT * FROM student WHERE id in <foreach collection="list" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
-
sql
可将重复的SQL片段提取出来,然后在需要的地方,使用
<include>
标签进行引用<select id