spring3 + mybatis自定义typeHandler

时间:2013-03-06 09:38:11

标签: spring mybatis typehandler

我有一个类型为Set<String>的字段的pojo。 我想将它们作为json持久保存在db中,所以我创建了一个自定义的typeHandler,但是当我尝试持久化时,我得到错误:没有找到TypeHandler ....

 testSave(it.infora.suap.service.MailMessageServiceTest): nested exception is org.apache.ibatis.executor.ExecutorException: There was no TypeHandler found for parameter recipients_to of statement it.infora.suap.persistence.MailMessageMapper.insertEmailMessage

Set<String>

中的参数recipients_to

这是我的自定义typeHandler类:

public class SetTypeHandler implements TypeHandler<Set<String>>{


    @Override
    public void setParameter(PreparedStatement ps, int columnIndex, Set<String> parameter, JdbcType jt) throws SQLException {
    ps.setString(columnIndex,  serializeToJson(parameter));
    }

    @Override
    public Set<String> getResult(ResultSet rs, String columnName) throws SQLException {
        return deserializeFromJson(rs.getString(columnName));
    }

    @Override
    public Set<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
        return deserializeFromJson(rs.getString(columnIndex));
    }

    @Override
    public Set<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return deserializeFromJson(cs.getString(columnIndex));
    }

    private String serializeToJson(Set<String> parameter){
        Gson gson = new Gson();
        return gson.toJson(parameter);
    }

    private Set<String> deserializeFromJson(String value){
        Gson gson = new Gson();
        Type collectionType = new TypeToken<Set<String>>(){}.getType();
        Set<String> result  = gson.fromJson(value, collectionType);

        return result;       
    }

}

怎么了?我正在使用带注释的mapper接口而不是mapper.xml

由于

安德烈

1 个答案:

答案 0 :(得分:3)

我找到了一些信息herehere,但似乎你错过了

@MappedTypes(Set.class) 
public class SetTypeHandler implements TypeHandler<Set<String>>{