mybatis里mapper.xml中SQL语句if语句嵌套if语句

x33g5p2x  于2022-01-04 转载在 其他  
字(0.7k)|赞(0)|评价(0)|浏览(332)

为了实现一个sql可以根据条件不同实现sql语句的动态查询,所以在使用mybatis时,对应的mapper.xml的sql语句可以根据条件值的不同执行不同的sql语句,
最开始在我的where子句中我的if语句是这么写的:

<where>
			<if test="status==0 ">
				 status=#{status}
			</if>
			 <if test="status==1">
				 status=#{status}
			</if>
			<if test="status==2">
				 status=#{status}
			</if>
	    	<if test="status==-1">
				 status=0 or status=2 
	    	</if> 
    	</where>

需要实现当status为空的时候,没有status的条件,为0,1,2的时候按照status的值查询,这样实在太笨,所以修改如下:

<where>
		<if test="status!=null">
			<if test="status==0 or status==1 or status==2">
				 status=#{status}
			</if>
			<if test="status==-1">
				 status=0 or status=2 
	    	</if> 
		</if>
   </where>

这样可以实现同样的效果,只有status不为null的时候才有条件查询,当为空的时候无条件查询,这样就简洁多了,看着也舒服!

相关文章

微信公众号

最新文章

更多