mybatis jdbcType与javaBean之间转换处理

文章目录

    • Mapper 文件配置
    • java pojo
    • 转换处理类

完整的依赖关系如下图:
mybatis jdbcType与javaBean之间转换处理_第1张图片

Mapper 文件配置


    
    
    
    
    
  

注意上述PROPERTIES属性中的typeHandler是转换的关键

java pojo

@Data
public class CheckinConfig {
    private Long checkinId;

    private Short type;

    private Date startDate;

    private Date endDate;

    private Map properties;

    public static final String POSTER_QR_CODE = "posterQrCode";

}

转换处理类

import com.fasterxml.jackson.annotation.JsonInclude;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.MappedTypes;


/**
 * @author : yanzy
 * @date : 2019-03-20
 */
@MappedTypes(Map.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MybatisJsonTypeHandler extends BaseTypeHandler {

    private static final ObjectMapper mapper = new ObjectMapper();
    private Class clazz;

    public MybatisJsonTypeHandler(Class clazz) {
        if (clazz == null) throw new IllegalArgumentException("Type argument cannot be null");
        this.clazz = clazz;
    }

    public MybatisJsonTypeHandler() {
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, this.toJson(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.toObject(rs.getString(columnName), clazz);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getString(columnIndex), clazz);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getString(columnIndex), clazz);
    }

    private String toJson(T object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private T toObject(String content, Class clazz) {
        if (content != null && !content.isEmpty()) {
            try {
                return (T) mapper.readValue(content, clazz);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }

    static {
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
}

此类扩展了mybatis提供的BaseTypeHandler类,我们只需要自定义一个转换方法,如上例中的toObject()方法,然后重写getNullableResult()方法的所有重载,在其中运用转换方法,并返回结果即可。

你可能感兴趣的:(mybatis)