会员中心 足迹 动态 消息 创作中心 发布 MyBatis动态拼接SQL

1,590 阅读1分钟

通过使用MyBatis提供的标签方法可以实现动态SQL拼接

1、if标签

<select id="findUser" parameterType="org.mybatis.demo.po.User"
	resultType="org.mybatis.demo.po.User">
	select * from user
	where 1=1
	<if test="id!=null and id!=''">
		and id=#{id}
	</if>
	<if test="username!=null and username!=''">
		and username like '%${username}%'
	</if>
</select>

以上SQL语句表示,如果POJO类中id值不为空,则把id作为条件进行检索;如果username属性值不为空,则把username作为条件进行检索;如果id和username都不为空,则把id和username都作为条件进行检索

2、where标签

<select id="findUser1" parameterType="org.mybatis.demo.po.User"
	resultType="org.mybatis.demo.po.User">
	select * from user
	<where>
		<if test="id!=null and id!=''">
			and id=#{id}
		</if>
		<if test="username!=null and username!=''">
			and username like '%${username}%'
		</if>
	</where>
</select>

where标签的作用是可以自动处理掉第一个and(可以参考if标ids为QueryVO对象的属性,属性的类型为List。foreach标签签

3、foreach标签通过POJO传递List集合

<!-- 通过pojo传递list -->
<select id="findUsersByIds" parameterType="org.mybatis.demo.po.QueryVO"
	resultType="org.mybatis.demo.po.User">
	select * from user
	<where>
		<if test="ids!=null and ids.size>0">
		    <!-- open:循环开始 close:循环结束 separator:中间的分隔符 -->
			<foreach collection="ids" open=" and id in(" close=")" item="id"
				separator=",">
				#{id}
			</foreach>
		</if>
	</where>
</select>

package org.mybatis.demo.po;
 
import java.util.List;
 
public class QueryVO {
 
	private List<Integer> ids;
 
	public List<Integer> getIds() {
		return ids;
	}
 
	public void setIds(List<Integer> ids) {
		this.ids = ids;
	}
 
}

foreach标签的open属性表示循环开始;close属性表示循环结束;separator属性表示每次循环中间的分隔符

4、foreach标签传递单个List集合

<!-- 传递list -->
<select id="findUsersByIds1" parameterType="java.util.List"
	resultType="org.mybatis.demo.po.User">
	select * from user
	<where>
		<if test="list!=null">
			<foreach collection="list" open=" and id in(" close=")"
				item="item" separator=",">
				#{item}
			</foreach>
		</if>
	</where>
</select>

foreach标签的open属性表示循环开始;close属性表示循环结束;separator属性表示每次循环中间的分隔符。注意,此时select标签的parameterType属性值为java.util.List

5、foreach标签传递数组

<select id="findUsersByIds2" parameterType="Object[]"
	resultType="org.mybatis.demo.po.User">
	select * from user
	<where>
		<if test="array!=null">
			<foreach collection="array" open=" and id in(" close=")"
				item="item" separator=",">
				#{item}
			</foreach>
		</if>
	</where>
</select>

foreach标签的item属性为数组的每个元素的名称,名称可以随意定义;open属性表示循环开始;close属性表示循环结束;separator属性表示每次循环中间的分隔符。

6、SQL片段的使用

声明SQL片段

<!-- 声明SQL片段 -->
<sql id="query_user_where">
	<if test="id!=null and id!=''">
		and id=#{id}
	</if>
	<if test="username!=null and username!=''">
		and username like '%${username}%'
	</if>
</sql>

引用SQL片段

<!-- 引用sql片段 -->
<select id="findUser2" parameterType="org.mybatis.demo.po.User"
	resultType="org.mybatis.demo.po.User">
    select * from user 
    <where>
        <include refid="query_user_where"></include>
    </where>
</select>