Mybatyis foreache 标签
在Mybatis的xml配置中使用集合,主要是用到了foreach动态语句。
foreach的参数:
foreach元素的属性主要有 item,index,collection,open,separator,close。
item表示集合中每一个元素进行迭代时的别名.
index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置(不知道具体的用处).
open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符.
close表示以什么结束
问题:
在使用mybatis中使用 foreach 出现如下问题
org.apache.ibatis.reflection.ReflectionException:There is no getter for property named '__frch_item_0' in 'TestEntity'
foreach 代码如下:
<foreach collection="companys" index="index" item="item" open=" (" close=") " separator=",">
#{item}
</foreach>
问题分析:
这边使用了一个第三方分页插件
com.github.miemiedev.mybatis.paginator.domain.PageBounds;
查询一:this.getSqlSession().selectList(toMybatisStatement("selectByConditions"), params, bounds);
查询二:this.getSqlSession().selectList(toMybatisStatement("selectByConditions"), params);
使用第一种带第三方分页插件查询 报错:
org.apache.ibatis.reflection.ReflectionException:There is no getter for property named '__frch_item_0' in 'TestEntity'
使用第二种方式查询 能够正常使用。
解决方案
如果想要使用第一种查询方式时 可以使用一下两种解决方法:
解决方案1:parameterType 参数类型将 TestEntity 修改成 map
解决方案2:将 #{item} 修改成 ${item} 如果是字符串则修改成 '${item}'
mybatis 中 #{}与${}的区别
默认情况下,使用#{}语法,MyBatis会产生PreparedStatement语句中,并且安全的设置PreparedStatement参数,这个过程中MyBatis会进行必要的安全检查和转义。
示例1:
执行SQL:Select * from company where id = #{id}
参数:id =>10
解析后执行的SQL:Select * from emp where id= ?
执行SQL:Select * from company where id= ${id }
参数:id 传入值为:10
解析后执行的SQL:Select * from company where id=10
使用foreach循环的时候 companys 这边传入的是string 数组
使用foreach循环时 默认会 将item 转成 __frch_item_0 ...
1.我们使用#{} 获取参数 则变成 __frch_item_0=>10... Select * from emp where id in(?,?,?)
2.我们使用${} 获取参数 则变成 10 传入数据中 .. Select * from emp where id in(10,20,30) 则可以直接使用
所以在使用分页查询的时候使用第二种解决方案是可行的。那是什么原因导致了使用#{}这种获取参数数据的方式会错,而当使用map作为参数时#{}又是可用的。
分析数据:在使用#{}获取参数时,mybatis会将获取到的数据存入一个map中,
例如:
{id="10",param1 = "test",_fors_item_0=591,_fors_item_1=592 }
其中 低于param1为正常获取 数据,_fors_item_0,_fors_item_1为循环时获取的数据,
同时在map还会有其他的参数,其中包括 传入类型 parameterType所带入的对象(TestEntity)。
可能性分析解析:
使用PageBounds 的时候会将mybaits 的数据嵌入在PageBounds里面,
个人分析在PageBounds 回填参数的时候做了类型的判断,
判断传入的parameterType是否是map类型,如果是则从map中获取数据,如果不是则将map映射成TestEntity实体,然而在实体中不存在_fors_item_0属性,所以就提示错误:
org.apache.ibatis.reflection.ReflectionException:There is no getter for property named '__frch_item_0' in 'TestEntity'
总结 :
使用${}方式会引发SQL注入的问题、同时也会影响SQL语句的预编译,所以从安全性和性能的角度出发,能使用#{}的情况下就不要使用${},