1. 程式人生 > >mybitis下choose..when. otherwise條件不起作用

mybitis下choose..when. otherwise條件不起作用

我的程式碼如下:

      <select id="findList" resultType="TyArticle">
		SELECT 
			<include refid="tyArticleColumns"/>
		FROM ty_article a
		<include refid="tyArticleJoins"/>
		<where>
			a.del_flag = #{DEL_FLAG_NORMAL}
			<if test="enVersion != null and enVersion != ''">
				AND a.en_version = #{enVersion}
			</if>
			<if test="category != null and category != ''">
				AND a.category = #{category}
			</if>
			<if test="top != null and top != ''">
				AND a.top = #{top}
			</if>
			<if test="title != null and title != ''">
				AND a.title LIKE 
					<if test="dbName == 'oracle'">'%'||#{title}||'%'</if>
					<if test="dbName == 'mssql'">'%'+#{title}+'%'</if>
					<if test="dbName == 'mysql'">concat('%',#{title},'%')</if>
			</if>
		</where>
		<choose>
			<when test="enVersion != null and enVersion =='0'">
				order by a.weight desc ,str_to_date(a.publish_date, '%Y年%m月%d日') desc
			</when>
			<otherwise>
				order by a.weight desc ,str_to_date(a.publish_date, '%d %M %Y') desc
			</otherwise>
		</choose>
	</select>

  choose...when...otherwise語法,when中的條件不起作用,不管條件是不是0,都取otherwise中的結果。

       首先,仔細檢查語法格式,感覺沒有問題啊,怎麼就不起作用呢?

       其次,有檢查呼叫sql時傳遞的引數enVersion也是String型別,所以書寫也沒問題啊。

       最後,檢查資料中enVersion的資料型別,發現是char(1),於是把程式碼條件換成這樣,再測試,

          <choose>
			<when test="enVersion != null and enVersion == 0 ">
				order by a.weight desc ,str_to_date(a.publish_date, '%Y年%m月%d日') desc
			</when>
			<otherwise>
				order by a.weight desc ,str_to_date(a.publish_date, '%d %M %Y') desc
			</otherwise>
		</choose>

  結果,成功了。原來資料再判斷引數型別時,還跟引數在表中對應的資料型別有關。在引數比較的過程直接轉成了int型,所以把

enVersion =='0', 改成 enVersion == 0,問題解決。

總結在此,期望對以後有所幫助。