放入<result>标记</result>时,未执行MyBatis自定义TypeHandler

时间:2013-11-21 13:21:51

标签: java mybatis typehandler

对于其中一个结果属性,我有<resultMap>个自定义typeHandler

<resultMap id="foo" type="hashmap">
    ... 
    <result property="SERVICES_XML" javaType="string" jdbcType="CLOB" typeHandler="com.foo.bar.OracleClobTypeHandler" />
    ...
</resultMap>

无论我将哪个属性附加到我的处理程序(我的意思是不是CLOB特定的问题,也尝试使用VARCHAR),处理程序将不会被调用从数据库中获取结果。

我在自定义处理程序的所有方法中都设置了断点:

public class OracleClobTypeHandler implements TypeHandler<String> {

  @Override
  public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
    log.debug("setParameter called");   <================ BREAKPOINT HERE
  }

  @Override
  public String getResult(ResultSet rs, String columnName)
        throws SQLException {
    log.debug("getResult 2 called");    <================ BREAKPOINT HERE
    return "";
  }

  @Override
  public String getResult(ResultSet rs, int columnIndex)
        throws SQLException {
    log.debug("getResult 2 called");    <================ BREAKPOINT HERE
    return "";
  }

  @Override
  public String getResult(CallableStatement cs, int columnIndex)
        throws SQLException {
    log.debug("getResult 3 called");    <================ BREAKPOINT HERE
    return "";
  }
}

显然,上述方法均未执行。

我已尝试将<typeHandler javaType="java.lang.String" jdbcType="CLOB" handler="com.foo.bar.OracleClobTypeHandler"/>放入myBatis <configuration>,但这也不起作用。
也没有做任何其他事情,包括扩展TypeHandler<Object>等等。

我做错了什么?

2 个答案:

答案 0 :(得分:4)

经过长时间的挖掘,我终于找到了答案。

这似乎是myBatis中的一个错误。

为了让处理程序适用于<result>元素,您必须明确指定column属性,即使property属性已经与bean中的列名和字段名匹配即可。
就我而言,它看起来像这样:

 <result property="SERVICES_XML" column="SERVICES_XML" javaType="string" jdbcType="CLOB" typeHandler="com.foo.bar.OracleClobTypeHandler" />

请注意,上述更改还会导致<configuration>标记中定义的处理程序生效,因此可能不再需要内联typeHandler - 这就是我的情况。我最终得到了:

<configuration>
  <typeHandlers>
    <typeHandler javaType="java.lang.String" jdbcType="CLOB" handler="com.foo.bar.OracleClobTypeHandler"/>        
  </typeHandlers>
</configuration>

<result property="SERVICES_XML" column="SERVICES_XML" javaType="string" jdbcType="CLOB" />

答案 1 :(得分:3)

虽然这个问题现在已经有3年了,但我更倾向于认为这个问题与Oracle&#39; 大写&#39;从结果元数据中检索的列名称,而区分大小写的java对象属性名称通常尊重camel case。

然后,除非在SQL查询中使用带引号的别名,否则需要显式列属性映射。 The question has been asked here。 与最新评论中所说的不同,我观察到ORDER BY引用了别名。