package com.ces.config;

import com.ces.ObjectMapperUtils;
import com.ces.pojo.User;
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;

@MappedJdbcTypes(JdbcType.VARCHAR)
public class UserHandler extends BaseTypeHandler<User> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, User parameter, JdbcType jdbcType) throws SQLException {
        String userJson = ObjectMapperUtils.toJSON(parameter);
        ps.setString(i,userJson);
    }

    @Override
    public User getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String userJson = rs.getString(columnName);
        return  ObjectMapperUtils.toObject(userJson, User.class);
    }

    @Override
    public User getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String userJson=rs.getString(columnIndex);
        return ObjectMapperUtils.toObject(userJson,User.class);
    }

    @Override
    public User getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String userString = cs.getString(columnIndex);
        return ObjectMapperUtils.toObject(userString,User.class);
    }
}
