根據條件查詢數據列表,mybatis查詢代碼以下java
若是隻查詢屬於特定部門擁有的數據權限。這須要用 String[ ] codes保存當前部門及其子部門的部門編碼。spring
因此須要在mybatis中遍歷編碼數組。sql
<select id="findList" resultType="xx.entity.Xxxx"> SELECT ${sqlMap.column.toSql()} FROM ${sqlMap.table.toSql()} <where> ${sqlMap.where.toSql()} <if test="codes != null and codes.length > 0"> AND u5.office_code in <foreach item="code" index="index" collection="codes" open="(" separator="," close=")"> ${code} </foreach> </if> </where> ORDER BY ${sqlMap.order.toSql()} </select>
上面的代碼會在僅查詢部門範圍的數據時報錯。數據庫
Error querying database. Cause: java.sql.SQLException: 在將 varchar 值 'SD' 轉換成數據類型 int 時失敗。apache
緣由是 ${ } 符號獲取數組值時,不會在值兩邊添加引號 ' ' 查詢數據庫時,可能默認爲這個in裏面的是int數值,因此報類型轉換異常。數組
還原真實sql以下 (數據庫的部門編碼是字符串值。)mybatis
select * from data a left join user u on u.user_code=a.createBy left join employee e on e.emp_code=u.ref_code left join office o on o.office_code=e.office_code where a.status='0' and o.office_code in (001016,003,004,005,006,008,007)
就在想,既然是沒加引號的問題,那我改用 #{ }這個符號來取值不就好的app
<if test="codes != null and codes.length > 0"> AND u5.office_code in <foreach item="code" index="index" collection="codes" open="(" separator="," close=")"> #{code} </foreach> </if>
再次嘗試仍是不行。此次報差錯不同了編碼
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named '__frch_code_0' in 'class'spa
沒有找到對應的get的屬性方法。以爲默認覺得我這個是一個實體類,而後以get方式獲取值,但我這裏明顯是String[ ] 數組形式的數據。
再從網上搜索資料。還有一種用法
<if test="codes != null and codes.length > 0"> AND u5.office_code in <foreach item="code" index="index" collection="codes" open="(" separator="," close=")"> #{codes[${index}]} </foreach> </if>
這種仍是會報錯。
nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.IllegalStateException: Type handler was null on parameter mapping for property 'codes[0]'. It was either not specified and/or could not be found for the javaType ([Ljava.lang.String;) : jdbcType (null) combination.
### Cause: java.lang.IllegalStateException: Type handler was null on parameter mapping for property 'codes[0]'. It was either not specified and/or could not be found for the javaType ([Ljava.lang.String;) : jdbcType (null) combination.
最後,仍是使用 '${ }'
用美圓符號在左右兩邊加引號方式解決問題。
<if test="codes != null and codes.length > 0"> AND u5.office_code in <foreach item="code" index="index" collection="codes" open="(" separator="," close=")"> '${code}' </foreach> </if>