1. 程式人生 > >mybatis的查詢語句

mybatis的查詢語句

原先mapper中的sql是

	<select id="queryByModelId" resultType="java.util.Map">
	   select  * from  ldp_analy_model_select
	  WHERE 
	     <if test="modelId != null">
          model_id = #{modelId}
         </if>
         <if test="fieldType != null">
            and field_type = #{fieldType}
         </if>
	</select>
	
	如果這些條件沒有一個能匹配上將會怎樣?最終這條 SQL 會變成這樣:select  * from  ldp_analy_model_select  WHERE   
	這會導致查詢失敗。如果僅僅第二個條件匹配又會怎樣?這條 SQL 最終會是這樣: select  * from  ldp_analy_model_select  WHERE   AND field_type = #{fieldType}
最終的sql語句為
<select id="queryByModelId" resultType="java.util.Map">
      select  * from  ldp_analy_model_select
      <trim  prefix="where"  prefixOverrides="and|or">
         <if test="modelId != null">
            and model_id = #{modelId}
         </if>
         <if test="fieldType != null">
            and field_type = #{fieldType}
         </if>
      </trim>
  </select>
引用 https://www.cnblogs.com/caoyc/p/5574966.html    https://www.cnblogs.com/qiankun-site/p/5758924.html

當mybatis使用查詢時  使用傳入的引數為map時  應當如何解決

<select id="queryMyApplyList" parameterType="java.util.Map"
		resultMap="BaseResultMap">
		SELECT id,apply_name,start_time,expire_time,`status`,update_time,
		(select `name` from ldp_sys_user where id = create_by ) create_name
		FROM `ldp_mgmt_apply` where create_by = ${userId}
		<if test="status != null and status != ''">
			and status = ${status}
		</if>
		<if test="KeyWord != null and KeyWord != ''">
			and apply_name like '%${KeyWord}%'
		</if>
		order by update_time desc
</select>

當mapper檔案方法中的引數只有一個時,是預設填充的  比如

	/**
	 * 根據ID查詢
	 * @param applyId
	 * @return
	 */
	public  ApplyBean  queryApplyById(Integer applyId);
<select id="queryApplyById" resultMap="BaseResultMap"   parameterType="java.lang.Integer">
        select <include refid="Base_Column_List" />  from ldp_mgmt_apply
	where id = #{id,jdbcType=INTEGER}
</select>
這樣也可以查出來的 將applyId的值賦給id    可直接填充