Mybatis关于<foreach>中的index判断提示“Inappropriate OGNL expression”

来源:互联网 发布:win10端口设置在哪里 编辑:程序博客网 时间:2024/06/07 08:34

最近公司的项目在用mybatis作为持久层框架,我在使用的过程中出现了这样的一个需求:

在分表的数据中实现跨表查询,先将表名存储在一个List中,而后在mybatis中遍历这个list,同时在循环一个List过程中,需要对第一条与最后一条添加额外的SQL语句(需要增加时间的判断)。

在跨表查询中使用了UNION ALL来连接查询的结果,因此得到了如下的代码:

<select id="findAttendList" resultType="Attend">        <if test="tableNames.size() > 0">        SELECT*FROM<foreach collection="tableNames" item="tmpTableName" index="index" open="(" close=") tmp" separator="UNION ALL">SELECT        <include refid="attendColumns" />FROM ${tmpTableName} a<if test="(workername!=null and workername!='') or (workeridno!=null and workeridno!='')">LEFT JOIN        tb_worker b on a.worker_id = b.id</if><where>       a.del_flag = #{DEL_FLAG_NORMAL}        AND                                <!-- 这里需要判断是否是第一张表,第一张表需要增加额外的查询条件 --><if test="0 = index and begdate != null">AND a.attend_date >= date_format(#{begdate},'%y%m%d')</if>                                <!-- 这里需要判断是否是最后一张表,最后一张表需要增加额外的查询条件 --><if test="index + 1 = tableNames.size() and enddate != null">AND a.attend_date <= date_format(#{enddate},'%y%m%d')</if></where></foreach>ORDER BY tmp.attendDate ASC</if></select>

这样写好之后,一运行就一直提示“Inappropriate OGNL expression:0”(不适合的OGNL表达式),我就想到是不是将0作为了OGNL表达式,于是我把"0 = index",改成了“index=0”,发现这里就不再报错了,但是又出现了“Inappropriate OGNL expression: (index + 1)”,这样的问题说明与上面类似,mybatis不能识别这个表达式,因此我就将上面的“index + 1=tableNames.size()”改成了“index=tableNames.size() - 1”,就不再报错,能够正常运行了。

下面是修改之后的代码:

<select id="findAttendList" resultType="Attend"><if test="tableNames.size() > 0">SELECT*FROM<foreach collection="tableNames" item="tmpTableName" index="index" open="(" close=") tmp" separator="UNION ALL">SELECT<include refid="attendColumns" />FROM ${tmpTableName} a<if test="(workername!=null and workername!='') or (workeridno!=null and workeridno!='')">LEFT JOIN tb_worker b on a.worker_id = b.id</if><where>        a.del_flag = #{DEL_FLAG_NORMAL}AND<!-- 这里修改成index=0 --><if test="index = 0 and begdate != null">AND a.attend_date >= date_format(#{begdate},'%y%m%d')</if>                                <!-- 这里修改成index=tableNames.size() - 1 --><if test="index = tableNames.size() - 1 and enddate != null">AND a.attend_date <= date_format(#{enddate},'%y%m%d')</if></where></foreach>ORDER BY tmp.attendDate ASC</if></select>
至于为什么会出现这个问题,由于目前对mybatis的理解还不到位,它的机制也不大清楚(正在努力中),如果有高手知道,请一定在评论区指出,将不胜感激