package com.bohuikeji.frame.module.admin.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数组转换器
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(String[].class)
public class MybatisArryTypeHandler extends BaseTypeHandler<String[]> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        StringBuilder pics=new StringBuilder();
        for(String pic:parameter){
            pics.append(pic);
            pics.append(",");
        }
        ps.setString(i,pics.toString());
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String column=rs.getString(columnName);
        if (column==null){
            return null;
        }
        return column.split(",");
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String column=rs.getString(columnIndex);
        if (column==null){
            return null;
        }
        return column.split(",");
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String column=cs.getString(columnIndex);
        if (column==null){
            return null;
        }
        return column.split(",");
    }
}
