mybatis {arg0} 與 {0}


解決方案:

MyBatis的XML的配置文件中聲明設置屬性的useActualParamName參數值為假

<setting name="useActualParamName" value="false" />

代碼展示:

Dao層函數

User getUserBys(int id,String name);

對應的mapping.xml

 
<select id="getUserBys" resultType="model.User">
 
select * from user where id = #{0} and name=#{1}
 
</select>

這種方法應該是對的,但是如果你使用的是mybatis3.4.2或者之后的版本,就會產生綁定異常:

org.apache.ibatis.binding.BindingException: Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2]

從異常可以看出在沒有使用@參數注解的情況下,傳遞參數需要使用

#{}為arg0 - #{} ARGN#或者{}參數1 - #{} paramn

  • 更換下mapping.xml中的代碼
<select id="getUserBys" resultType="model.User">
 
select * from user where id = #{arg0} and name=#{arg1}
 
</select>

此時代碼就會正常運行


下面貼上3.4.1以及之前版本的綁定異常信息:

 org.apache.ibatis.binding.BindingException: Parameter 'arg0' not found. Available parameters are [0, 1, param1, param2]

可以發現3.4.1版本中傳遞參數可以使用#{0} - #{N}

問題原因

MyBatis的通過XMLConfigBuilder類來加載配置文件中的各項參數

  • 3.4.2版本之前設置屬性中useActualParamName參數的默認值為flase 
    XMLConfigBuilder.class的settingsElement方法中的源代碼
configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true)); 

 

  • 3.4.2版本之后設置屬性中useActualParamName參數的默認值為true 
    XMLConfigBuilder.class的settingsElement方法中的源代碼
configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), false));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM