【问题标题】:mybatis jdbc select query is not working throws Invalid column indexmybatis jdbc 选择查询不工作抛出无效的列索引
【发布时间】:2019-02-07 11:07:42
【问题描述】:

我在 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

【问题讨论】:

  • 可能用于 OUTER JOIN。尝试使用 LEFT OUTER JOIN 重写并在 toad 或 SQL plus 中执行
  • 不,这与 JPA API 无关

标签: java jdbc mybatis spring-mybatis


【解决方案1】:

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

当你使用#{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}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    相关资源
    最近更新 更多