代码之家  ›  专栏  ›  技术社区  ›  sunleo

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

  •  0
  • sunleo  · 技术社区  · 6 年前

    我在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 回复  |  直到 6 年前
        1
  •  1
  •   Roman-Stop RU aggression in UA    6 年前

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

    当你使用像 #{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 = '?'
    

    JDBCAPI将其视为一个没有任何参数的查询,因此当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}")