1. 程式人生 > >Mybatis寫mapper對映檔案中的注意事項

Mybatis寫mapper對映檔案中的注意事項

xml中某些特殊符號作為內容資訊時需要做轉義,否則會對檔案的合法性和使用造成影響

Html程式碼 複製程式碼 收藏程式碼
  1. &lt; <
  2. &gt; >
  3. &amp; &
  4. &apos; '
  5. &quot; "
&lt; < 
&gt; > 
&amp; & 
&apos; ' 
&quot; "

在mapper檔案中寫sql語句時,為避免不必要的麻煩(如<等),建議使用<![CDATA[ ]]>來標記不應由xml解析器進行解析的文字資料,由<![CDATA[ ]]>包裹的所有的內容都會被解析器忽略 <![CDATA[ sql語句 ]]>

Xml程式碼 複製程式碼 收藏程式碼
  1. <select id="getAccountsByBranch" resultType="Account" parameterType="string">
  2. <![CDATA[SELECT * FROM t_acctreg_accounts where acctno < #{acctno}]]>
  3. </select>

將整個sql語句用<![CDATA[ ]]>標記來避免衝突,在一般情況下都是可行的,但是如果這樣寫

Xml程式碼 複製程式碼 收藏程式碼
  1. <select id="getAccountErrorCount" resultType="int" parameterType="map">
  2. <![CDATA[
  3. select count(*) from t_acctreg_accounterror
  4. <where>
  5. <if test="enddate != null and enddate != ''">
  6. createdate <= #{enddate}
  7. </if>
  8. <if test="acctno != null and acctno != ''">
  9. AND acctno LIKE '%'||#{acctno}||'%'
  10. </if>
  11. </where>
  12. ]]>
  13. </select>

就會收到錯誤資訊:

org.springframework.jdbc.UncategorizedSQLException: Error setting null parameter. Most JDBC drivers require that the JdbcType must be specified for all nullable parameters. Cause: java.sql.SQLException: 無效的列型別: 1111 ; uncategorized SQLException for SQL []; SQL state [99999]; error code [17004]; 無效的列型別: 1111; nested exception is java.sql.SQLException: 無效的列型別: 1111

這是由於該sql配置中有動態語句(where,if),where,if 條件不能放在<![CDATA[ ]]>中,否則將導致無法識別動態判斷部分,導致整個sql語句非法.應該縮小範圍,只對有字元衝突部分進行合法性調整

Xml程式碼 複製程式碼 收藏程式碼
  1. <select id="getAccountErrorCount" resultType="int" parameterType="map">
  2. select count(*) from t_acctreg_accounterror
  3. <where>
  4. <if test="enddate != null and enddate != ''">
  5. <![CDATA[createdate <= #{enddate}]]>
  6. </if>
  7. <if test="acctno != null and acctno != ''">
  8. <![CDATA[AND acctno LIKE '%'||#{acctno}||'%']]>
  9. </if>
  10. </where>
  11. </select>

還有在向oracle插入資料時,mybatis3報Error setting null parameter. Most JDBC drivers require that the JdbcType must be specified for all nullable parameters,是由於引數出現了null值,對於Mybatis,如果進行操作的時候,沒有指定jdbcType型別的引數,mybatis預設jdbcType.OTHER導致,給引數加上jdbcType可解決(注意大小寫)

http://code.google.com/p/mybatis/issues/detail?id=224&q=Error%20setting%20null%20parameter&colspec=ID

Xml程式碼 複製程式碼 收藏程式碼
  1. <insert id="insertAccountError" statementType="PREPARED"
  2. parameterType="AccountError">
  3. INSERT INTO t_acctreg_accounterror(createdate,acctno, errorinfo)
  4. VALUES(#{createdate,jdbcType=DATE},#{acctno,jdbcType=VARCHAR},#{errorinfo,jdbcType=VARCHAR})
  5. </insert>