mybatis jdbc select查询不起作用引发无效的列索引

时间:2019-02-07 11:07:42

标签: java jdbc mybatis spring-mybatis

我的mybatis版本3中存在以下问题。请帮助我找到它。

Java代码:

@Select("SELECT A.PERSON_ID,A.PERSON_ADDRESS, C.CUSTOMER_NAME," + 
            "       B.CUSTOMER_DOB," + 
            "   FROM PERSON A, CUSTOMER B, CUSTOMER_DETAILS C" + 
            "  WHERE A.CUSTOMER_ID=C.CUSTOMER_ID" + 
            "  AND A.CUSTOMER_ID=B.CUSTOMER_ID (+)" + 
            "  AND C.PERSON_NAME='#{personName, jdbcType=VARCHAR,    mode=IN,  javaType=String}'" + 
            "  AND C.CUSTOMER_ID='#{customerID, jdbcType=VARCHAR,    mode=IN,  javaType=String}'")
    @Results(value = {
       @Result(property = "personId", column = "PERSON_ID"),
       @Result(property = "personAddress", column = "PERSON_ADDRESS"),
       @Result(property = "customerName", column = "CUSTOMER_NAME"),
       @Result(property = "customerDOB", column = "CUSTOMER_DOB")
    })
    List<PersonCustomerDetail> getPersonCustomerByID(@Param("personName") String personName,@Param("customerID") String customerID);

异常跟踪:

nested exception is org.apache.ibatis.type.TypeException: 
Could not set parameters for mapping: ParameterMapping{property='personName', mode=IN, javaType=class java.lang.String, jdbcType=VARCHAR, 
numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. 
Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #1 with JdbcType VARCHAR . 
Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.sql.SQLException: Invalid column index

1 个答案:

答案 0 :(得分:1)

问题在于参数传递给查询。

使用=Sumif($A$2:$C$5,A8,$B$2:$D$5)之类的表达式指定参数时,mybatis会将其转换为jdbc参数占位符#{parameterName},然后按索引设置参数。对于此查询:

?

mybatis生成的查询为:

 select * from  a where col = #{param}

因为您引用了这样的参数:

 select * from a where col = ?

生成的查询变为:

 select * from  a where col = '#{param}'

并且JDBC API将其视为没有任何参数的查询,因此当mybatis尝试使用JDBC select * from a where col = '?' API设置参数时,错误是参数索引无效。

要解决此问题,请删除引号:

PreparedStatement