package com.cesgroup.homwork.mybatis.sample.type;

import cn.hutool.json.JSONUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
/**
 * map类型转换器
 */
public class MapTypeHandler extends BaseTypeHandler<Map> {
    public MapTypeHandler() {
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map map, JdbcType jdbcType) throws SQLException {
        ps.setString(i,JSONUtil.toJsonStr(map));
    }

    @Override
    public Map getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return rs.wasNull() ? null : JSONUtil.parseObj(result);
    }
    @Override
    public Map getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        return  rs.wasNull() ? null : JSONUtil.parseObj(result);
    }
    @Override
    public Map getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        return cs.wasNull() ? null : JSONUtil.parseObj(result);
    }
}