dryu999 发表于 2016-11-26 09:18:50

mybatis写mapper文件注意事项

  xml中某些特殊符号作为内容信息时需要做转义,否则会对文件的合法性和使用造成影响

Html代码


[*]&lt;<
[*]&gt;>
[*]&amp;&
[*]&apos;'
[*]&quot;"

  在mapper文件中写sql语句时,为避免不必要的麻烦(如<等),建议使用<!]>来标记不应由xml解析器进行解析的文本数据,由<!]>包裹的所有的内容都会被解析器忽略 <!]>
Xml代码


[*]<selectid="getAccountsByBranch"resultType="Account"parameterType="string">
[*]<!]>
[*]</select>

  将整个sql语句用<!]>标记来避免冲突,在一般情况下都是可行的,但是如果这样写
Xml代码


[*]<selectid="getAccountErrorCount"resultType="int"parameterType="map">
[*]<![CDATA[
[*]selectcount(*)fromt_acctreg_accounterror
[*]<where>
[*]<iftest="enddate!=nullandenddate!=''">
[*]createdate<=#{enddate}
[*]</if>
[*]<iftest="acctno!=nullandacctno!=''">
[*]ANDacctnoLIKE'%'||#{acctno}||'%'
[*]</if>
[*]</where>
[*]]]>
[*]</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 ; uncategorizedSQLException for SQL []; SQL state ; error code ; 无效的列类型: 1111; nested exception is java.sql.SQLException: 无效的列类型: 1111
  这是由于该sql配置中有动态语句(where,if),where,if 条件不能放在<!]>中,否则将导致无法识别动态判断部分,导致整个sql语句非法.应该缩小范围,只对有字符冲突部分进行合法性调整
Xml代码


[*]<selectid="getAccountErrorCount"resultType="int"parameterType="map">
[*]selectcount(*)fromt_acctreg_accounterror
[*]<where>
[*]<iftest="enddate!=nullandenddate!=''">
[*]<!]>
[*]</if>
[*]<iftest="acctno!=nullandacctno!=''">
[*]<!]>
[*]</if>
[*]</where>
[*]</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代码


[*]<insertid="insertAccountError"statementType="PREPARED"
[*]parameterType="AccountError">
[*]INSERTINTOt_acctreg_accounterror(createdate,acctno,errorinfo)
[*]VALUES(#{createdate,jdbcType=DATE},#{acctno,jdbcType=VARCHAR},#{errorinfo,jdbcType=VARCHAR})
[*]</insert>
页: [1]
查看完整版本: mybatis写mapper文件注意事项