我的代碼如下:
<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,問題解決。
總結在此,期望對以后有所幫助。