如果使用函数时,第一个拼接语句多一个运算符,可以通过以下两种方式解决:

  1. 使用函数判断是否为第一个元素,如果是则不拼接运算符

例如:

<select id="selectByIds" parameterType="list" resultType="User">
    SELECT * FROM user WHERE id IN
    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
        <if test="index > 0">AND</if>
        #{item}
    </foreach>
</select>
  1. 将第一个元素作为一个特殊情况处理,先将其拼接到SQL语句中,然后在函数中使用separator属性指定分隔符,这样就可以避免第一个元素多拼接一个运算符。

例如:

<select id="selectByIds" parameterType="list" resultType="User">
    SELECT * FROM user WHERE id = #{list[0]}
    <foreach item="item" index="index" collection="list" open=" AND id IN (" separator="," close=")">
        #{item}
    </foreach>
</select>
``

原文地址: https://www.cveoy.top/t/topic/fpLf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录