在MyBatis Mapper中使用Postgres && 语句时出现错误
MyBatis中Postgres数组交集查询报错解决
原Postgres可行查询语句
在PgAdmin中可正常运行的数组交集判断查询:
SELECT * FROM weather_schema.weather weather WHERE STRING_TO_ARRAY(weather.phenoms, ',') && '{"TO", "WI"}'
问题中的MyBatis Mapper配置
尝试用可注入的字符串列表phenoms替换固定数组的Mapper配置:
<select id="getFilteredWeather" resultMap="WeatherObj"> SELECT * FROM weather_schema.weather weather WHERE string_to_array(weather.custom_phenoms, ',') && <foreach item="phenom" index="," collection="phenoms" open="&#39;{&quot;" separator="&quot;,&quot;" close="&quot;}&#39;"> #{phenom} </foreach> </select>
报错信息
执行时触发如下错误:
org.mybatis.spring.MyBatisSystemException] with root cause org.postgresql.util.PSQLException: The column index is out of range: 7, number of columns: 6.
问题原因
原写法错误地将MyBatis预编译参数#{phenom}嵌入到字符串常量的数组格式中,生成的SQL会类似'{"?","?"}'。Postgres会将整个字符串视为单个数组元素,而MyBatis会把每个?当作独立的预编译参数,导致参数数量与查询预期不匹配,触发索引越界错误。
解决方案
方案1:使用Postgres数组构造器
直接用array[]语法构造数组,配合MyBatis的foreach生成预编译参数:
<select id="getFilteredWeather" resultMap="WeatherObj"> SELECT * FROM weather_schema.weather weather WHERE string_to_array(weather.custom_phenoms, ',') && array[ <foreach item="phenom" collection="phenoms" separator=","> #{phenom} </foreach> ] </select>
方案2:使用MyBatis数组类型处理器
如果你的MyBatis版本支持数组类型处理,可以直接传入List<String>并指定类型处理器,让MyBatis自动转换为Postgres数组:
<select id="getFilteredWeather" resultMap="WeatherObj"> SELECT * FROM weather_schema.weather weather WHERE string_to_array(weather.custom_phenoms, ',') && #{phenoms, typeHandler=org.apache.ibatis.type.ArrayTypeHandler} </select>
注意:使用此方案时,需要确保项目中包含对应的类型处理器依赖,且参数phenoms的类型为List<String>或String[]。
内容的提问来源于stack exchange,提问作者drocky
相关产品推荐
相关产品推荐

