简体   繁体   中英

spring3 + mybatis custom typeHandler

i have a pojo with some field of type Set<String> . 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 ....

 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>

this is my custom typeHandler class:

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

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>>{

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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