mybatis對傳入基本類型參數(shù)的判斷方式
對傳入基本類型參數(shù)的判斷
mybatis的xml文件的sql語句中parameterType為基本類型,如:
<select id="getCustomer" parameterType="Integer" resultType="Customer">
? ? select * from customer
? ? where
? ? <if test="id != null">id=#{id}</if>
<select>會報錯:There is no getter for property named 'id' in 'class java.lang.Integer'
這是因為Integer對象中沒有id屬性
解決辦法
<select id="getCustomer" parameterType="Integer" resultType="Customer">
? ? select * from Customer
? ? where
? ? <if test="_parameter != null">id=#{_parameter}</if>
<select>即將接收參數(shù)的參數(shù)名改為_parameter,注意改成其他參數(shù)名沒用。
傳入基本類型參數(shù)時test判斷報錯
在使用mybatis的時候出現(xiàn)了這樣的問題:
//Dao層的接口中的代碼 List<Map<String,Object>> getName(String username);
//對應的mapper中的代碼
<select id="getName" resultType="java.util.Map">
?? ?select name,client_id
?? ?from table1
?? ?<where>?
?? ? ? ?<if test=" username!= null and username!='' ">
?? ??? ??? ?and username= #{id}
?? ??? ?</if>
?? ?</where>?
</select>//報的錯誤
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException:
There is no getter for property named 'username' in 'class java.lang.String'
分析
There is no getter for property named ‘username’ in ‘class java.lang.String’,這句話打大概意思是:在“class java.lang.String”中沒有名為“username”的屬性的getter方法。因為mybatis默認采用ONGL解析參數(shù),所以會自動采用對象樹的形式取string.num值,引起錯誤。
解決辦法
if test中的id用_parameter替換,而實際的語句不需要修改and a.id =#{id},因為Mybatis當只傳入一個參數(shù)時#{ } 中的內(nèi)容沒有要求。
在Mapper中給出入?yún)⒃O(shè)置名稱,例:public … getName(@Param(“username”) String username);這樣修改后我們前面的寫法就不會報錯了。
小結(jié)一下
在傳入基本類型的數(shù)據(jù)時,if標簽中test判斷的書寫hi根據(jù)ognl表達式來取值的,所以不能直接寫參數(shù)的名稱,要利用_parameter來替代,或者利用注解@Pram("")來給參數(shù)起別名。
補充一點點:標簽when中的test屬性也有同樣的問題!??!
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring?BeanFactory?與?FactoryBean?的區(qū)別詳情
這篇文章主要介紹了Spring?BeanFactory?與?FactoryBean?的區(qū)別詳情,BeanFactory?和?FactoryBean?的區(qū)別卻是一個很重要的知識點,在本文中將結(jié)合源碼進行分析講解,需要的小伙伴可以參考一下2022-05-05
JavaWeb Struts文件上傳功能實現(xiàn)詳解
這篇文章主要為大家詳細介紹了JavaWeb Struts文件上傳功能實現(xiàn)過程,思路清晰,供大家參考,感興趣的小伙伴們可以參考一下2016-06-06
IDEA如何使用spring-Initializr快速搭建SpringBoot
這篇文章主要介紹了IDEA如何使用spring-Initializr快速搭建SpringBoot問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05

