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否則拼接不上條件參數 。

           mybatis3.1.1可以正常執行,其它版本未測試!!!


缺點:where中的多個條件之間只支持and;

           where中不支持多個範圍條條件;

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章