在用Mybatis時遇到了一個讓我折騰了一晚上的問題(好歹接觸Mybatis半年多了,自我感覺不應該存在什么致命盲區了),誰知道這個問題直接把人給干傻了。
先描述問題情況:當時正在寫一個接收json數組(用戶的ID),來批量刪除用戶的代碼。我將數據封裝到了int數組中(因為只是一個很簡單的內部管理系統,就直接用整型做的ID)。mapper內容如下:
<!--邏輯刪除用戶-->
<update id="deleteByIds">
update staff set deleted = 1
where id in
<foreach collection="array" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</update>
寫完以后自然要測試,一測試就報了下面的異常:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: java.lang.ClassCastException: class [I cannot be cast to class [Ljava.lang.Object; ([I and [Ljava.lang.Object; are in module java.base of loader 'bootstrap')
### The error may exist in file [F:\geek-and-hard-workingbee-member-management\target\classes\mappers\StaffMapper.xml]
### The error may involve com.geekbee.membermanagement.mapper.StaffMapper.deleteByIds
### The error occurred while executing an update
### Cause: java.lang.ClassCastException: class [I cannot be cast to class [Ljava.lang.Object; ([I and [Ljava.lang.Object; are in module java.base of loader 'bootstrap')
從報錯上看,說是I(如果了解過Java虛擬機應該知道在虛擬機內部是用I來表示int的)不能轉化為Object(前面的L表示這是引用類型),其實這個報錯是很明確的,但我不信邪啊。開了Debug,打算看看為會這樣(為什么Mybatis可以接受int做參數,卻不能接收int數組)。
結果Debug顯示數組內容是正常的,但是Mybatis的方法內部調用壓根沒法看,反復試了幾次,受不了了,就把int數組改成了String數組,一測試,OK了。
直接說結論,Mybatis似乎是不能接受基本數據類型數組的,保險起見可以直接用String數組,當然也可以用包裝類數組試試。