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

92 阅读1分钟

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标签签

作者:大坏蛋_
链接:juejin.cn/post/716988…
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。