mybatis根据参数动态拼接多个where条件

          在工作中使用mybatis对单表查询操作时,因为查询条件的不同而在mapper文件中写多条sql语句,导致mapper文件臃肿。为了解决这一问题,希望通过传递不同参数mybatis自动拼接sql语句。

DAO 文件中方法:

       selectByCondtions(@Param("condition")Map param )

       param中保存条件参数对应不同的条件格式如下:

              where   filed=value:

                      {field:value}

              where file in (value1,value2,....)

                      {"listKey":"id","listValues":Arrays.asList("1","2")}

              limit 0,10

                      {"limit":"0,10"}

              order by id desc

                      {"order by":"id desc"}

 

mapper 文件:

 

 <select id="selectByCondtions" resultMap="BaseResultMap">
		select
		<include refid="Base_Column_List" />
		FROM rt_stu_submit_state
		 <where> 
			<foreach collection="condition.keys" item="k1" separator="and">
				<if test="condition[k1] != null and condition[k1] != '' ">
					<choose>
				 		<when test="'listKey' == k1 ">
							${condition.listKey} in
							<foreach collection="condition.listValues" item="v" separator="," open="(" close=")">
									#{v}
							</foreach>
						</when>
						<when test="'order'!=k1 and 'listValues' != k1 and 'limit' != k1 ">
							${k1} = #{condition[${k1}]}
						</when>
					</choose>
				</if>
				<if test="condition[k1] == null or condition[k1] == '' ">
					(${k1} is null or ${k1} = '')
				</if>
			</foreach>
		</where>
		<if test="condition.order !=null and condition.order !=''">
			order by ${condition.order}
		</if>
		<if test="condition.limit !=null and condition.limit !=''">
			limit  ${condition.limit}
		</if>
	</select> 

 

 

注意:表中的字段名不要包含k1否则拼接不上条件参数 。

           mybatis  3.1.1 、3.4.6 可以正常执行,其它版本未测试!!!

 

缺点:where中的多个条件之间只支持and;

 

           where中不支持多个范围条条件;
 

希望看到此文章的同学有好的思路可以给我留言,一起交流学习!!!

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值