mybatis jdbc select 查询不工作抛出无效的列索引

mybatis jdbc select query is not working throws Invalid column index

我在 mybatis 版本中遇到以下问题 3.Please 帮我找到这个。

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

问题出在传递给查询的参数上。

当你使用像#{parameterName}这样的表达式来指定一个参数时,mybatis会将其转换为jdbc参数占位符?,然后通过索引设置参数。对于此查询:

 select * from  a where col = #{param}

mybatis 生成的查询将是:

 select * from a where col = ?

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

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

生成的查询变为:

 select * from  a where col = '?'

而这被 JDBC API 视为不带任何参数的查询,因此当 mybatis 尝试使用 JDBC PreparedStatement API 设置参数时错误是参数索引无效。

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

@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}")