Mybatis通用JSON Type Handler

项目中使用postgresql的json类型存储了些数据。为了实现po中的类和json之间的转换,写了个通用的JSON Type Handler,分享出来。

 

使用jackson来实现json和object之间转换。
使用的时候在resultMap中,对应的列配置,例如:

Mapper XML中配置的update/insert语句需要指明typeHandler

update table_xxx 
      set colA=#{beanA.xxx, typeHandler=cn.devmgr.tutorial.typehandler.JsonTypeHandler}
      where id=xx

JsonTypeHandler.java (继承Mybatis提供的BaseTypeHandler,很简单,关键是范型的处理)

package cn.devmgr.tutorial.typehandler;
 
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class JsonTypeHandler extends BaseTypeHandler {
    private final static Log log = LogFactory.getLog(JsonTypeHandler.class);
     
    private static ObjectMapper objectMapper;
    private Class type;
    static {
        objectMapper = new ObjectMapper();
    }
     
    public JsonTypeHandler(Class type) {
        if(log.isTraceEnabled()) {
            log.trace("JsonTypeHandler(" + type + ")");
        }
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }
     
    private  T parse(String json) {
        try {
            if(json == null || json.length() == 0) {
                return null;
            }
            return objectMapper.readValue(json, type);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
     
    private String toJsonString(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
     
    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return (T) parse(rs.getString(columnName));
    }
 
    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return (T) parse(rs.getString(columnIndex));
    }
 
    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return (T) parse(cs.getString(columnIndex));
    }
 
    @Override
    public void setNonNullParameter(PreparedStatement ps, int columnIndex, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(columnIndex, toJsonString(parameter));
         
    }
 
}

最后,推荐一个spring免费课程:用Spring Boot编写RESTful API

http://study.163.com/course/introduction.htm?courseId=1005213034

原文

你可能感兴趣的:(Mybatis通用JSON Type Handler)