在MyBatis中使用模糊查詢的幾種方式

1.使用${...}

    <select id="selectAll" parameterType="map" resultMap="BaseResultMap">
    	SELECT
			*
		FROM
			insurance_base_info
		WHERE
			1 = 1
		<if test="date!=null and date!=''">
			and insurance_apply_date=#{date}
		</if>
		<if test="insuranceMan!=null and insuranceMan!=''">
			and insurance_apply_man LIKE '%${insuranceMan}%'
		</if>
		<if test="isPay!=null and isPay!=''">
			and is_paid=#{isPay}
		</if>
    </select>

注意:由於$是參數直接注入的,導致這種寫法,大括號裏面不能註明jdbcType,不然會報錯

2.使用#{...}

    <select id="selectAllInsurancePay" parameterType="map" resultMap="BaseResultMap">
    	SELECT
			*
		FROM
			insurance_base_info
		WHERE
			1 = 1
		<if test="date!=null and date!=''">
			and insurance_apply_date=#{date}
		</if>
		<if test="insuranceMan!=null and insuranceMan!=''">
			and insurance_apply_man LIKE "%"#{insuranceMan}"%"
		</if>
		<if test="isPay!=null and isPay!=''">
			and is_paid=#{isPay}
		</if>
    </select>

注意:因爲#{...}解析成sql語句時候,會在變量外側自動加單引號'  ',所以這裏 % 需要使用雙引號"  ",不能使用單引號 '  ',不然會查不到任何結果。

3.使用CONCAT()函數連接參數形式

    <select id="selectAllInsurancePay" parameterType="map" resultMap="BaseResultMap">
    	SELECT
			*
		FROM
			insurance_base_info
		WHERE
			1 = 1
		<if test="date!=null and date!=''">
			and insurance_apply_date=#{date}
		</if>
		<if test="insuranceMan!=null and insuranceMan!=''">
			and insurance_apply_man LIKE  CONCAT('%',#{insuranceMan},'%')
		</if>
		<if test="isPay!=null and isPay!=''">
			and is_paid=#{isPay}
		</if>
    </select>

 

發佈了46 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章