總結(jié)一些基礎(chǔ)的常見的Mybatis問題,方便自己,方便讀者學(xué)習(xí),內(nèi)容不多
使用 mybatis 時(shí) sql 語(yǔ)句是寫在 xml 文件中,如果 sql 中有一些特殊的字符的話,比如< ,<=,>,>=等符號(hào),會(huì)引起 xml 格式的錯(cuò)誤,需要替換掉,或者不被轉(zhuǎn)義。 有兩種方法可以解決:轉(zhuǎn)義字符和標(biāo)記 CDATA 塊。
方式1、轉(zhuǎn)義字符
1 <select id="searchByPrice" parameterType="Map" resultType="Product">
2 <!-- 方式1、轉(zhuǎn)義字符 -->
3 select * from Product where price >= #{minPrice} and price <= #{maxPrice}
4 </select>
方式2、標(biāo)記 CDATA
1 <select id="searchByPrice" parameterType="Map" resultType="Product">
2 <!-- 方式2、CDATA -->
3 <![CDATA[select * from Product where price >= #{minPrice} and price <= #{maxPrice} ]]>
4 </select>
轉(zhuǎn)義字符表
轉(zhuǎn)義 | 符號(hào) |
---|---|
< | < |
> | > |
& | & |
' | ’ |
" | “ |
網(wǎng)上的總結(jié)很多,簡(jiǎn)單而言,resultType 用于返回值只有一個(gè)字段的類型,resultMap 用于返回值有多個(gè)字段的類型。至于結(jié)果是 List 還是一個(gè),則在 Mapper 中定義返回值是List還是單個(gè)。
使用 resultType:
1 <select id="count" resultType="java.lang.Integer">
2 SELECT count(*) FROM USER
3 </select>
使用 resultMap:
1 <resultMap type="com.liulanghan.Blog" id="BlogResult">
2 <id column="id" property="id"/>
3 <result column="title" property="title"/>
4 <result column="content" property="content"/>
5 <result column="owner" property="owner"/>
6 </resultMap>
7
8 <select id="selectBlog" parameterType="int" resultMap="BlogResult">
9 select * from t_blog where id = #{id}
10 </select>
Mapper 中需要用 @Param("queryDate")定義參數(shù)名稱,sql 中用#{queryDate}使用參數(shù),字符串也不需要引號(hào)。
參數(shù)判斷和if的用法:
1 <if test="queryDate != null">
2 and queryDate >= #{queryDate}
3 </if>
when otherwise 就是 if else
1 <choose>
2 <when test="isDelete != null and isDelete == 0">
3 isDelete=0
4 </when>
5 <otherwise>
6 isDelete=1
7 </otherwise>
8 </choose>
如果要判斷的字符串,則需要加引號(hào)
1 <when test="gender != null and gender == 'MALE'">
2 gender='MALE'
3 </when>
場(chǎng)景是這樣的,需要做一個(gè)對(duì)賬單查詢,可以按金額范圍進(jìn)行查詢,頁(yè)面參數(shù)寫完之后進(jìn)行條件,輸入0測(cè)試了無(wú)數(shù)次均失效。
當(dāng)頁(yè)面參數(shù)為 0,傳入到 mybatis 的 xml 中后,如果不是字符串,需指定數(shù)據(jù)類型,否則會(huì)被誤認(rèn)為 null
<if test="data.tatalAmount != null and data.totalAmount !='' ">
and total_Amount=#{data.totalAmount}
</if>
這種情況如果 totalAmount 為 0 時(shí)將被誤認(rèn)為是 null,里面的條件不會(huì)執(zhí)行。正確的姿勢(shì)如下
1.添加 0 判斷
<if test="data.tatalAmount != null and data.totalAmount !='' or tatalAmount==0 ">
and total_Amount=#{data.totalAmount}
</if>
2.規(guī)定傳入?yún)?shù)的類型
<if test="data.tatalAmount != null and data.totalAmount !='' ">
and total_Amount=#{data.totalAmount,jdbc.Type=DECIMAL}
</if>
更多建議: