简体   繁体   English

spring3 + mybatis自定义typeHandler

[英]spring3 + mybatis custom typeHandler

i have a pojo with some field of type Set<String> . 我有一些类型为Set<String>字段的pojo。 I want to persist them in the db as json, so i create a custom typeHandler, but when i try to persist i get the error: There was no TypeHandler found .... 我想将它们作为json持久保存在数据库中,所以我创建了一个自定义的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

the parameter recipients_to in a Set<String> Set<String>的参数receivers_to

this is my custom typeHandler class: 这是我的自定义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;       
    }

}

what's wrong? 怎么了? I'm using annotated mapper interface instead of mapper.xml 我正在使用带注释的mapper接口而不是mapper.xml

Thanks 谢谢

Andrea 安德里亚

I found some information here and here , but it seems that you missed 我在这里这里找到了一些信息,但似乎您错过了

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM